Csharp/C#教程:从日期时间到字符串格式的转换错误分享


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

这部分代码有问题,我正在尝试将记录插入到我的预订表中。 我想输入的值是(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值与字符串连接一起使用(on + operator),则会自动为它们调用.ToString方法,并且您可能会为数据库列生成“正确”的文本。 不要为列选择错误的数据类型 。 您需要直接传递DateTime值。 如果您不知道,您知道哪个SqlDbType值,您也可以阅读Mapping CLR Parameter Data 。

正如评论中所建议的那样,解决此类情况的最佳方法是使用参数化查询 。 另一方面,这些字符串连接对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附带以下数据类型,用于在数据库中存储日期或日期/时间值:

上述就是C#学习教程:从日期时间到字符串格式的转换错误分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/988554.html

(0)
上一篇 2021年12月24日
下一篇 2021年12月24日

精彩推荐