简体   繁体   中英

C# string was not recognized as a valid DateTime in Parameters.AddWithValue

I am working on C# .net, i want to insert a date time which is of 12 chunk. Bellow is my code

cmd2.Parameters.AddWithValue("@Occurrence_Time", Convert.ToDateTime(Meter_data.Substring(161, 12)));
cmd2.Parameters.AddWithValue("@Recovery_Time", Convert.ToDateTime(Meter_data.Substring(173, 12)));

While running my program i'am getting the following error

string was not recognized as a valid DateTime

Using Quick Watch the date time is like 161025120830 and while inserting it the date time should be like 2016-10-25 12:08:30

In above line the date starts with 16 but in Database it should be inserted as 2016

Updated Code

As suggested by un-lucky , I have made the following changes to the code, See bellow

try
{
    con.Open();
    cmd1.Parameters.AddWithValue("@Device_ID", device_Id);
    cmd1.Parameters.AddWithValue("@Energy_kWh", Convert.ToDecimal(Meter_data.Substring(18, 9)));
    cmd1.Parameters.AddWithValue("@Power_kW", Convert.ToDecimal(Meter_data.Substring(144, 7)));
    cmd1.Parameters.AddWithValue("@Voltage_Phase_1", Convert.ToDecimal(Meter_data.Substring(102, 6)));
    cmd1.Parameters.AddWithValue("@Voltage_Phase_2", Convert.ToDecimal(Meter_data.Substring(109, 6)));
    cmd1.Parameters.AddWithValue("@Voltage_Phase_3", Convert.ToDecimal(Meter_data.Substring(116, 6)));
    cmd1.Parameters.AddWithValue("@Current_Phase_1", Convert.ToDecimal(Meter_data.Substring(123, 6)));
    cmd1.Parameters.AddWithValue("@Current_Phase_2", Convert.ToDecimal(Meter_data.Substring(130, 6)));
    cmd1.Parameters.AddWithValue("@Current_Phase_3", Convert.ToDecimal(Meter_data.Substring(137, 6)));
    cmd1.Parameters.AddWithValue("@Device_Serial_Number", Meter_data.Substring(152, 8));

    //For Events


    string formatString = "yyMMddHHmmss";
    DateTime Occurrence_Time, Recovery_Time;
    string strOccurrence = Meter_data.Substring(161, 12);
    string strRecovery = Meter_data.Substring(173, 12);


    cmd2.Parameters.AddWithValue("@Device_ID", device_Id);
    cmd2.Parameters.AddWithValue("@Event_ID", event_Id);

    if (DateTime.TryParseExact(strOccurrence, formatString, CultureInfo.InvariantCulture, DateTimeStyles.None, out Occurrence_Time))
    {
        if (DateTime.TryParseExact(strRecovery, formatString, CultureInfo.InvariantCulture, DateTimeStyles.None, out Recovery_Time))
        {
            cmd2.Parameters.Add("@Occurrence_Time", SqlDbType.DateTime).Value = Occurrence_Time;
            cmd2.Parameters.Add("@Recovery_Time", SqlDbType.DateTime).Value = Recovery_Time;
        }
    }



    //cmd2.Parameters.AddWithValue("@Occurrence_Time", Convert.ToDateTime(Meter_data.Substring(161, 12)));
    //cmd2.Parameters.AddWithValue("@Recovery_Time", Convert.ToDateTime(Meter_data.Substring(173, 12)));

    int ADS_Device_Data_rows_executed = cmd1.ExecuteNonQuery();
    Console.WriteLine("Rows Executed: '{0}'", ADS_Device_Data_rows_executed);

    int Device_Events_rows_executed = cmd2.ExecuteNonQuery();
    Console.WriteLine("Rows Executed: '{0}'", Device_Events_rows_executed);
    con.Close();
    Console.WriteLine("Data Recieved correctly and Stored in Data Base : {0}", DateTime.Now);

}
catch (Exception ex)
{
    Console.WriteLine(" >> " + ex.ToString());
    Console.WriteLine("Data Recieved is Incorrect Data is not stored in DB : {0}", DateTime.Now);
}

While debugging when the pointer comes at if (DateTime.TryParseExact(strOccurrence, formatString, CultureInfo.InvariantCulture, DateTimeStyles.None, out Occurrence_Time))

It doesn't goes in it and gives the exception Must declare the scalar variable "@Occurrence_Time".

Moreover there may be more than one Occurrence Time and Recover Time , but for now it's just for one event time

I have searched many articles on this exception but couldn't find any accurate solution for Parameters.AddWithValue

Updated Code 2

Following a suggestion i have done the following changes in my code

        string formatString = "yyyyMMddHHmmss";
        DateTime Occurrence_Time ,Recovery_Time;
        string strOccurrence = "20" + Meter_data.Substring(161, 12);
        string strRecovery = "20" + Meter_data.Substring(173, 12);

        if (DateTime.TryParseExact(strOccurrence, formatString, CultureInfo.InvariantCulture, DateTimeStyles.None, out Occurrence_Time))
            {
                if (DateTime.TryParseExact(strRecovery, formatString, CultureInfo.InvariantCulture, DateTimeStyles.None, out Recovery_Time))
                {
                    cmd2.Parameters.Add("@Occurrence_Time", SqlDbType.DateTime).Value = Occurrence_Time;
                    cmd2.Parameters.Add("@Recovery_Time", SqlDbType.DateTime).Value = Recovery_Time;
                }
            }

At first run i was able to view correct data and inserted it successfuly, but now it's showing me empty see the picture bellow

在此处输入图片说明

Now again i am getting the same exception

Must declare the scalar variable "@Occurrence_Time".

Any help would be highly appreciated

The problem is with your Date/Time parsing, not the insertion. So you just need to provide the date time format as follows:

string formatString = "yyMMddHHmmss";
DateTime dt;
if (DateTime.TryParseExact(text, formatString, CultureInfo.InvariantCulture, 
                           DateTimeStyles.None,
                           out dt))

So the input for convert function is 161025120830 , and we can say that this will be in the format of yyMMddHHmmss So the best option for you to do this conversion is DateTime.TryParseExact , convert it and stored it in a variable and then use it for insertion. The code will be like this:

string formatString= "yyMMddHHmmss";
DateTime Occurrence_Time,Recovery_Time;
string strOccurrence = Meter_data.Substring(161, 12);
string strRecovery = Meter_data.Substring(173, 12);

if (DateTime.TryParseExact(strOccurrence,formatString, CultureInfo.InvariantCulture,DateTimeStyles.None,out Occurrence_Time))
{
    if (DateTime.TryParseExact(strRecovery,formatString, CultureInfo.InvariantCulture,DateTimeStyles.None,out Recovery_Time))
    {
      cmd2.Parameters.Add("@Occurrence_Time",SqlDbType.DateTime).Value=Occurrence_Time;
      cmd2.Parameters.Add("@Recovery_Time",SqlDbType.DateTime).Value=Recovery_Time;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM