这部分代码有问题,我正在尝试在我的预订表中插入一条记录。我试图输入的值是 (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();
}
我得到的错误如下,
“从字符串转换日期和/或时间时转换失败。”
我试图尽我所能研究这个问题,但我不知道如何解决这个问题。任何帮助表示赞赏。
好的,您的代码有一些问题。我将尝试按顺序解释所有这些。
首先,如果您使用DateTime
带有字符串连接的值(在+
运算符上),.ToString
方法会自动为它们调用,并且您可能会或可能不会为您的数据库列生成“正确”的文本。千万不能选择错误的数据类型的列。您需要直接传递您的DateTime
值。如果您不知道您知道哪个SqlDbType用于您的值,您也可以阅读映射 CLR 参数数据。
正如评论中所建议的,解决这种情况的最佳方法是使用参数化查询。另一方面,这些字符串连接对SQL 注入攻击是开放的。
还可以使用using
statement来自动处理您的连接(我们没有看到但......)和命令,而不是手动调用.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();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句