小编典典

从日期时间到字符串格式的转换错误

sql

我对这部分代码有疑问,我正在尝试在预订表中插入一条记录。我试图输入的值是(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();
        }

我收到的错误如下,

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

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


阅读 127

收藏
2021-05-16

共1个答案

小编典典

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

首先,如果您使用DateTime带有字符串连接的值(在+运算符上),.ToString则将自动为它们调用方法,并且您可能会为数据库列生成“正确的”文本。千万
不能 选择错误的数据类型的列
。您需要 直接*
传递您的DateTime价值。如果您不知道自己知道哪个SqlDbType作为值,则还可以读取Mapping
CLR参数数据
*

正如评论中所建议的那样,解决这种情况的最佳方法是使用参数化查询。另一方面,这些字符串连接对SQL注入攻击开放。

也可以使用using语句来自动处理连接(我们看不到,但是..)和命令,而不是手动调用.Dispose方法(您没有看到)。

举个例子;

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();
    }
}
2021-05-16