【问题标题】:error while import csv file datetime value into microsoft sql server将 csv 文件日期时间值导入 Microsoft SQL Server 时出错
【发布时间】:2022-11-23 09:55:28
【问题描述】:

错误; [System.InvalidCastException: '指定的转换无效。']

错误行:[ cmd.Parameters.AddWithValue("@DateTime", (DateTime)importRow["DateTime"]);]

using (SqlConnection conn =New SqlConnection(@"Data Source=BL03\SQLEXPRESS; Initial Catalog=HDB; User Id=sa; Password=00"))

    {

        conn.Open();
        foreach (DataRow importRow in S2P5.Rows)
        {

            SqlCommand cmd = new SqlCommand
                ("INSERT INTO S2P5 (DateTime,Miliseconds,MachineAutoStartStop,Pressure)" + "VALUES (@DateTime,@Miliseconds,@MachineAutoStartStop,@Pressure)", conn);

      
            cmd.Parameters.AddWithValue("@DateTime", (DateTime)importRow["DateTime"]);
            cmd.Parameters.AddWithValue("@Miliseconds", importRow["Miliseconds"]);
            cmd.Parameters.AddWithValue("@MachineAutoStartStop", importRow["MachineAutoStartStop"]);
            cmd.Parameters.AddWithValue("@Pressure", importRow["Pressure"]);
            

            cmd.ExecuteNonQuery();
        }

    }

【问题讨论】:

  • 你在importRow["DateTime"] 中有什么价值?
  • 请不要通过垃圾邮件标签来诱骗人们查看您的问题。此问题与 C 语言或 SSMS 或 WinForms 完全无关。

标签: c# csv casting


【解决方案1】:

您不能将某些东西转换为它还没有的类型。铸造不是转换。如果您正在读取 CSV 文件,那么所有内容都是 string。您需要将 string 转换为 DateTime。有多种方法可以做到这一点。如果保证数据是正确的,那么你可以使用DateTime.Parse.ParseExact。如果您还需要验证,请使用.TryParse.TryParseExact。您也应该将数字数据转换为数字。我怀疑你那里也有布尔数据,所以你也应该转换它。

【讨论】:

    猜你喜欢
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    • 2023-02-18
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多