[英]Conversion error from date time to string format
I have a problem with this section of code, I'm trying to insert a record into my booking table. 我对这部分代码有疑问,我正在尝试在预订表中插入一条记录。 The values I'm trying to input are (6, 3, 3, 20/06/2018 00:00:00, 400, 2800.00, True, 560.00) 我试图输入的值是(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();
}
The error I'm getting is as follows, 我得到的错误如下,
"Conversion failed when converting date and/or time from character string." “从字符串转换日期和/或时间时转换失败。”
I have tried to research the problem as best I can but I can't figure out how to fix this. 我已尽力研究此问题,但我不知道如何解决此问题。 Any help is appreciated. 任何帮助表示赞赏。
Okey, you have a few issues on your code. Okey,您的代码有一些问题。 I will try to explain all of them in order. 我将尝试按顺序解释所有这些内容。
First of all, if you use DateTime
values with string concatenation (on +
operator), .ToString
method automatically called for them and you get may or may not "proper" textual generated for your database column. 首先,如果将DateTime
值与字符串连接(在+
运算符上)一起使用, .ToString
方法将自动为其调用,并且您可能会或可能不会为数据库列“正确”生成文本。 Do not choose wrong data types for your columns . 不要选择错误的数据类型的列 。 You need to pass your DateTime
value directly . 您需要直接传递DateTime
值。 If you don't know, which SqlDbType you know for your values, you can read the Mapping CLR Parameter Data also. 如果您不知道自己的值知道哪个SqlDbType ,则还可以读取Mapping CLR参数数据 。
As suggested on the comments, best way to solve this kind of situations is using parameterized queries . 正如评论中所建议的那样,解决这种情况的最佳方法是使用参数化查询 。 On the other hand, these string concatenations are open for SQL Injection attacks. 另一方面,这些字符串连接对SQL注入攻击开放。
Also use using
statement to dispose your connection (which we don't see but..) and commands automatically instead of calling .Dispose
method (which you didn't) manually. 还可以使用using
语句自动处理连接(我们看不到,但是..)和命令,而不是手动调用.Dispose
方法 (您没有看到)。
As an example; 举个例子;
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();
}
}
To fix the error, use bookingDate.ToString("O")
. 要解决该错误,请使用bookingDate.ToString("O")
。
That being said, it is not considered a good practice to build your SQL query like that. 话虽这么说,构建这样的SQL查询并不是一种好的做法。 As mentioned in the comments, it is recommended that you use the Parameters
property of your SQLCommand
instance to avoid such problems. 如注释中所述,建议您使用SQLCommand
实例的Parameters
属性来避免此类问题。
SQL Server comes with the following data types for storing a date or a date/time value in the database: SQL Server带有以下数据类型,用于在数据库中存储日期或日期/时间值:
DATE - format YYYY-MM-DD. DATE-格式YYYY-MM-DD。
DATETIME - format: YYYY-MM-DD HH:MI:SS. DATETIME-格式:YYYY-MM-DD HH:MI:SS。
SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS. SMALLDATETIME-格式:YYYY-MM-DD HH:MI:SS。
TIMESTAMP - format: a unique number. TIMESTAMP-格式:唯一编号。
DateTime your_datetime_instance = DateTime.Now; var str = your_datetime_instance.ToString("yyyy-MM-dd");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.