[英]Conversion failed when converting date and/or time from character string error 4
[英]Conversion error from date time to string format
我对这部分代码有疑问,我正在尝试在预订表中插入一条记录。 我试图输入的值是(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();
}
我得到的错误如下,
“从字符串转换日期和/或时间时转换失败。”
我已尽力研究此问题,但我不知道如何解决此问题。 任何帮助表示赞赏。
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();
}
}
要解决该错误,请使用bookingDate.ToString("O")
。
话虽这么说,构建这样的SQL查询并不是一种好的做法。 如注释中所述,建议您使用SQLCommand
实例的Parameters
属性来避免此类问题。
SQL Server带有以下数据类型,用于在数据库中存储日期或日期/时间值:
DATE-格式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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.