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


