C# не записывается в базу данных - PullRequest
0 голосов
/ 04 августа 2020

Я читал разделы о вставке данных в базы данных, но явно не понял концепции. Я пытаюсь добавить значения переменных в локальный SQL Сервер Express, столбцы имеют то же имя, что и переменные. Я, по крайней мере, пытаюсь следить за другими сообщениями или документами Microsoft, но ясно, что я что-то упустил. Что мне нужно добавить, чтобы эта работа работала?

namespace WeatherAPIs
{
class API_Data_Mine
{
    static void Main(string[] args)
    {

        
        //Defines The client as WebClient and setup the HTTP Header
        using var client = new WebClient();
        client.Headers.Add("User-Agent", "C# Weather API");
        client.Headers.Add("Accept", "application/json");
        client.Headers.Add("Content-Type", "application/json");

        //Download the JSON result from the DarkSkyBaseURL on API_URL Class
        string darkskyresult = client.DownloadString(API_URL.DarkSkyBaseURL);
        var darkskyjson = JsonConvert.DeserializeObject(darkskyresult);
        //Print int the screen the result of the raw and unbeauty JSON download, wait for the user to press a key to resume
        Console.WriteLine(darkskyresult);

        string openWResult = client.DownloadString(API_URL.OpenWeatherBaseURL);
        var openWJson = JsonConvert.DeserializeObject(openWResult);
        //Print int the screen the result of the raw and unbeauty JSON download, wait for the user to press a key to resume
        Console.WriteLine(openWResult);

        string watherBitResult = client.DownloadString(API_URL.WeatherBitBaseURL);
        var weatherBitJson = JsonConvert.DeserializeObject(watherBitResult);
        //Print int the screen the result of the raw and unbeauty JSON download, wait for the user to press a key to resume
        Console.WriteLine(watherBitResult);

        //Parse and beautify the JSON Output from DarkSky URL
        JObject JDarkSKy = JObject.Parse(darkskyresult);
        JObject JopenW = JObject.Parse(openWResult);
        JObject JWeatherBit = JObject.Parse(watherBitResult);

        ////Write the beautified JSON from DarkSKy on screen and wait for the user to press a key to exit
        Console.WriteLine(JDarkSKy);
        Console.WriteLine(JopenW);
        Console.WriteLine(JWeatherBit);

        ///Mine the JSON selected JSON data and print it on screen

        var DSTemperature = (string)JDarkSKy.SelectToken("currently.temperature");
        var DSPressure = (string)JDarkSKy.SelectToken("currently.pressure");
        var DSWindSpeed = (string)JDarkSKy.SelectToken("currently.windSpeed");
        var DSRealFeel = (string)JDarkSKy.SelectToken("currently.apparentTemperature");
        var DSUvIndex = (string)JDarkSKy.SelectToken("currently.uvIndex");
        var DSHumidity = (string)JDarkSKy.SelectToken("currently.humidity");

        var OWTemperature = (string)JopenW.SelectToken("list[0].main.temp");
        var OWPressure = (string)JopenW.SelectToken("list[0].main.pressure");
        var OWWindSpeed = (string)JopenW.SelectToken("list[0].wind.speed");
        var OWRealFeel = (string)JopenW.SelectToken("list[0].main.feels_like");
        var OWHumidity = (string)JopenW.SelectToken("list[0].main.humidity");

        var WBSolarRadiation = (string)JWeatherBit.SelectToken("data[0].solar_rad");
        var WBUltraViolet = (string)JWeatherBit.SelectToken("data[0].uv");
        var WBWindSpeed = (string)JWeatherBit.SelectToken("data[0].wind_spd");
        var WBTemperature = (string)JWeatherBit.SelectToken("data[0].temp");
        var WPressure = (string)JWeatherBit.SelectToken("data[0].pres");
        var WBRealFeel = (string)JWeatherBit.SelectToken("data[0].app_temp");
        var WBHumidity = (string)JWeatherBit.SelectToken("data[0].rh");


        //UV only works wqith paid keys
        //var OWUvIndex = (string)JDarkSKy.SelectToken("list.main.");

        Console.WriteLine("Temperature on Dark Sky is - " + DSTemperature);
        Console.WriteLine("Pressure on Dark Sky is - " + DSPressure);
        Console.WriteLine("Wind Spped on Dark Sky is - " + DSWindSpeed);
        Console.WriteLine("Real Feel on Dark Sky is - " + DSRealFeel);
        Console.WriteLine("Ultra Violet Index on Dark Sky is - " + DSUvIndex);
        Console.WriteLine("Humidity Index on Dark Sky is - " + DSHumidity);

        Console.WriteLine("Temperature on Open Weather is - " + OWTemperature);
        Console.WriteLine("Pressure on Open Weather is - " + OWPressure);
        Console.WriteLine("Wind Spped on Open Weather is - " + OWWindSpeed);
        Console.WriteLine("Real Feel on Open Weather is - " + OWRealFeel);
        Console.WriteLine("Humidity on Open Weather is - " + OWHumidity);            

        Console.WriteLine("Solar Radiation on WeatherBit is - " + WBSolarRadiation);
        Console.WriteLine("Ultra Violet level on WeatherBit is - " + WBUltraViolet);
        Console.WriteLine("Wind Speed on WeatherBit is - " + WBWindSpeed);
        Console.WriteLine("Temperature on WeatherBit is - " + WBTemperature);
        Console.WriteLine("Pressure on WeatherBit is - " + WPressure);
        Console.WriteLine("Real Feel on WeatherBit is - " + WBRealFeel);
        Console.WriteLine("Humidity on WeatherBit is - " + WBHumidity);

        SqlConnection conn = new SqlConnection("Server=[ServerName];Database=WeatherValues;Trusted_Connection=true");
        conn.Open();
        SqlCommand insertCommand = new SqlCommand("INSERT INTO WeatherAPIs (DSPressure, DSWindSpeed, DSRealFeel, DSUvIndex, DSHumidity, OWTemperature, OWPressure, " +
            "OWWindSpeed, OWRealFeel, OWHumidity, WBSolarRadiation, WBUltraViolet, WBWindSpeed, WBTemperature, WPressure, WBRealFeel, WBHumidity) VALUES (@DSPressure, " +
            "@DSWindSpeed, @DSRealFeel, @DSUvIndex, @DSHumidity, @OWTemperature, @OWPressure, @OWWindSpeed, @OWRealFeel, @OWHumidity, @WBSolarRadiation, @WBUltraViolet, " +
            "@WBWindSpeed, @WBTemperature, @WPressure, @WBRealFeel, @WBHumidity)");

        insertCommand.Parameters.Add = ("@DSPressure", DSPressure);
        insertCommand.Parameters.Add = ("@DSWindSpeed", DSWindSpeed);
        insertCommand.Parameters.Add = ("@DSRealFeel", DSRealFeel);
        insertCommand.Parameters.Add = ("@DSUvIndex", DSUvIndex);
        insertCommand.Parameters.Add = ("@DSHumidity", DSHumidity);
        insertCommand.Parameters.Add = ("@OWTemperature", OWTemperature);
        insertCommand.Parameters.Add = ("@OWPressure", OWPressure);
        insertCommand.Parameters.Add = ("@OWWindSpeed", OWWindSpeed);
        insertCommand.Parameters.Add = ("@OWRealFeel", OWRealFeel);
        insertCommand.Parameters.Add = ("@OWHumidity", OWHumidity);
        insertCommand.Parameters.Add = ("@WBSolarRadiation", WBSolarRadiation);
        insertCommand.Parameters.Add = ("@WBUltraViolet", WBUltraViolet);
        insertCommand.Parameters.Add = ("@WBWindSpeed", WBWindSpeed);
        insertCommand.Parameters.Add = ("@WBTemperature", WBTemperature);
        insertCommand.Parameters.Add = ("@WPressure", WPressure);
        insertCommand.Parameters.Add = ("@WBRealFeel", WBRealFeel);
        insertCommand.Parameters.Add = ("@WBHumidity", WBHumidity);

    }
}
}

Я знаю, что здесь есть и другие сообщения об этом, но я просто не могу заставить это работать с материалами для чтения. : (

РЕДАКТИРОВАТЬ:

Я изменил следующее:

        DateTime now = DateTime.Now;
        Console.WriteLine("The System Date and Time is - " + now);

        SqlConnection conn = new SqlConnection("Server=[Server_Name];Database=WeatherValues;Trusted_Connection=true");
        conn.Open();


        SqlCommand insertCommand = new SqlCommand("INSERT INTO WeatherAPIs (DSPressure, DSWindSpeed, DSRealFeel, DSUvIndex, DSHumidity, OWTemperature, OWPressure, " +
            "OWWindSpeed, OWRealFeel, OWHumidity, WBSolarRadiation, WBUltraViolet, WBWindSpeed, WBTemperature, WPressure, WBRealFeel, WBHumidity) VALUES (@DSPressure, " +
            "@DSWindSpeed, @DSRealFeel, @DSUvIndex, @DSHumidity, @OWTemperature, @OWPressure, @OWWindSpeed, @OWRealFeel, @OWHumidity, @WBSolarRadiation, @WBUltraViolet, " +
            "@WBWindSpeed, @WBTemperature, @WPressure, @WBRealFeel, @WBHumidity)");

        insertCommand.Parameters.Add("@DSPressure", (System.Data.SqlDbType)DSPressure);
        insertCommand.Parameters.Add("@DSWindSpeed", (System.Data.SqlDbType)DSWindSpeed);
        insertCommand.Parameters.Add("@DSRealFeel", (System.Data.SqlDbType)DSRealFeel);
        insertCommand.Parameters.Add("@DSUvIndex", (System.Data.SqlDbType)DSUvIndex);
        insertCommand.Parameters.Add("@DSHumidity", (System.Data.SqlDbType)DSHumidity);
        insertCommand.Parameters.Add("@OWTemperature", (System.Data.SqlDbType)OWTemperature);
        insertCommand.Parameters.Add("@OWPressure", (System.Data.SqlDbType)OWPressure);
        insertCommand.Parameters.Add("@OWWindSpeed", (System.Data.SqlDbType)OWWindSpeed);
        insertCommand.Parameters.Add("@OWRealFeel", (System.Data.SqlDbType)OWRealFeel);
        insertCommand.Parameters.Add("@OWHumidity", (System.Data.SqlDbType)OWHumidity);
        insertCommand.Parameters.Add("@WBSolarRadiation", (System.Data.SqlDbType)WBSolarRadiation);
        insertCommand.Parameters.Add("@WBUltraViolet", (System.Data.SqlDbType)WBUltraViolet);
        insertCommand.Parameters.Add("@WBWindSpeed", (System.Data.SqlDbType)WBWindSpeed);
        insertCommand.Parameters.Add("@WBTemperature", (System.Data.SqlDbType)WBTemperature);
        insertCommand.Parameters.Add("@WPressure", (System.Data.SqlDbType)WPressure);
        insertCommand.Parameters.Add("@WBRealFeel", (System.Data.SqlDbType)WBRealFeel);
        insertCommand.Parameters.Add("@WBHumidity", (System.Data.SqlDbType)WBHumidity);
        //insertCommand.Parameters.Add("@DTTM", (System.Data.SqlDbType)now);

        insertCommand.ExecuteNonQuery();

        //Console.WriteLine("\nPress any key to resume.");            

        Console.ReadKey();

Теперь это дает мне эту ошибку:

    Severity    Code    Description Project File    Line    Suppression State
    Error   CS1656  Cannot assign to 'Add' because it is a 'method group'

1 Ответ

0 голосов
/ 04 августа 2020

Попробуйте изменить свой код на следующий код.

insertCommand.Parameters.Add("@YourParameter", System.Data.SqlDbType.NVarChar).Value = "Some of your values (no need to be string).";
// OR
insertCommand.Parameters.AddWithValue("@YourParameter", "Some of your values (no need to be string).");

, потому что вы вызываете .Add (string parameterName, SqlDbType sqlDbType), он просто подготавливает параметр и тип параметра, но фактическое значение не указывается.

...