简体   繁体   中英

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)

        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. 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. Do not choose wrong data types for your columns . You need to pass your DateTime value directly . If you don't know, which SqlDbType you know for your values, you can read the Mapping CLR Parameter Data also.

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.

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.

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") .

That being said, it is not considered a good practice to build your SQL query like that. As mentioned in the comments, it is recommended that you use the Parameters property of your SQLCommand instance to avoid such problems.

SQL Server comes with the following data types for storing a date or a date/time value in the database:

  • DATE - format YYYY-MM-DD.

  • DATETIME - format: YYYY-MM-DD HH:MI:SS.

  • SMALLDATETIME - format: YYYY-MM-DD HH:MI:SS.

  • TIMESTAMP - format: a unique number.

     DateTime your_datetime_instance = DateTime.Now; var str = your_datetime_instance.ToString("yyyy-MM-dd"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM