【问题标题】:Conversion error from date time to string format从日期时间到字符串格式的转换错误
【发布时间】:2018-10-02 15:32:49
【问题描述】:

这部分代码有问题,我正在尝试在我的预订表中插入一条记录。我要输入的值是 (6, 3, 3, 20/06/2018 00:00:00, 400, 2800.00, True, 560.00)

        public void insertBooking(int bookingID, int customerID, int entertainmentID, 
                                  DateTime bookingDate, int numberOfGuests, double price, 
                                  bool deposit, decimal depositPrice)
        {
            db.Cmd = db.Conn.CreateCommand();
            db.Cmd.CommandText = "INSERT INTO Booking (bookingID, customerID, entertainmentID, 
                                  [Booking Date], [Number Of Guests], [Price], [Deposit?], 
                                  [Deposit Price]) " + "Values ('" + bookingID + "','" + 
                                  customerID + "','" + entertainmentID + "','" + 
                                  bookingDate + "','" + numberOfGuests + "','" + price + 
                                  "','" + deposit + "','" + depositPrice + "')";
            db.Cmd.ExecuteNonQuery();
        }

我得到的错误如下,

"从字符转换日期和/或时间时转换失败 字符串。”

我已尽力研究此问题,但我不知道如何解决此问题。任何帮助表示赞赏。

【问题讨论】:

  • 学习使用参数进行查询。不要使用字符串常量进行查询。
  • 解决您的问题和 SQL 注入的方法总是相同的。使用参数
  • 对不起应该说它们是参数,我说我输入的值只是例子
  • @ConorCasey 那些不是 sql 参数。我们告诉你的是使用Command对象stackoverflow.com/questions/542510/…的Parameters集合
  • @Steve 哦,对了,我的错,我现在明白你的意思了,谢谢你的建议,但 Kzrystof 的回答仍然对我有用。谢谢大家。

标签: c# sql datetime sql-insert


【解决方案1】:

好的,您的代码有一些问题。我将尝试按顺序解释所有这些。

首先,如果您使用带有字符串连接的DateTime 值(在+ 运算符上),.ToString 方法会自动调用它们,您可能会或可能不会为您的数据库列生成“正确”的文本。 Do not choose wrong data types for your columns。您需要直接传递您的DateTime 值。如果您不知道哪个SqlDbType 是您的价值观,您也可以阅读Mapping CLR Parameter Data

根据 cmets 的建议,解决这种情况的最佳方法是使用 parameterized queries。另一方面,这些字符串连接对SQL Injection 攻击开放。

还可以使用using statement 自动处理您的连接(我们看不到,但是..)和命令,而不是手动调用.Dispose method(您没有)。

举个例子;

public void insertBooking(int bookingID, int customerID, int entertainmentID,
                          DateTime bookingDate, int numberOfGuests, double price,
                          bool deposit, decimal depositPrice)
{
    using (var con = new SqlConnection(yourConnectionString))
    using (var cmd = con.CreateCommand())
    {
        cmd.CommandText = @"INSERT INTO Booking (bookingID, customerID, entertainmentID, 
                            [Booking Date], [Number Of Guests], [Price], [Deposit?], 
                            [Deposit Price]) Values(@bookId, @cusId, @entId, @bookdate, @guests, @price, @deposit, @depositPrice)";
        cmd.Parameters.Add("@bookId", SqlDbType.Int).Value = bookingID;
        cmd.Parameters.Add("@cusId", SqlDbType.Int).Value = customerID;
        cmd.Parameters.Add("@entId", SqlDbType.Int).Value = entertainmentID;
        cmd.Parameters.Add("@bookdate", SqlDbType.DateTime).Value = bookingDate;
        cmd.Parameters.Add("@guests", SqlDbType.Int).Value = numberOfGuests;
        cmd.Parameters.Add("@price", SqlDbType.Decimal).Value = price;
        cmd.Parameters.Add("@deposit", SqlDbType.Bit).Value = deposit;
        cmd.Parameters.Add("@depositPrice", SqlDbType.Decimal).Value = depositPrice;

        con.Open();
        cmd.ExecuteNonQuery();
    }
}

【讨论】:

  • 谢谢,这解决了我所有的问题,对 SQL 来说相对较新,所以不是 100% 使用所有典型约定,但我肯定会从现在开始使用参数函数。非常感谢!
【解决方案2】:

要修复错误,请使用bookingDate.ToString("O")

话虽如此,这样构建 SQL 查询并不是一个好习惯。在cmets中提到,建议您use the Parameters property of your SQLCommand instance避免此类问题。

【讨论】:

    【解决方案3】:

    SQL Server 带有以下用于在数据库中存储日期或日期/时间值的数据类型:

    • 日期 - 格式 YYYY-MM-DD。

    • DATETIME - 格式:YYYY-MM-DD HH:MI:SS。

    • SMALLDATETIME - 格式:YYYY-MM-DD HH:MI:SS。

    • TIMESTAMP - 格式:一个唯一的数字。

      DateTime your_datetime_instance = DateTime.Now;
      var str = your_datetime_instance.ToString("yyyy-MM-dd");
      

    【讨论】:

    • 那是错误的。 SQL Server 不存储任何日期或日期时间数据类型的显示格式。它可以将特定格式的字符串隐式转换为 datetime 和 datetime2 - 这些格式是特定于文化的或 ISO 8601 - 因此对于日期使用 yyyy-MM-ddyyyyMMdd,对于 datetime - yyyy-MM-ddTHH:mm:ss。请注意,如果要转换为 DateTime,则从 DateTime 格式中省略 T 将使 Datetime 值区域性的字符串表示特定,但如果要转换为 DateTime2,则不会。
    猜你喜欢
    • 2014-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多