[英]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.