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");
Related
This question already has answers here:
insert datetime value in sql database with c#
(8 answers)
Closed 6 years ago.
string strQuery = "INSERT INTO [Order] (Quantity, Type, DateTime)
values( " + qty + "," + type + "," + dtstmp.ToString("yyyy-mm-dd hh:mm:ss.fff") + ")";
SQL Query:
INSERT INTO [Order] (Quantity, Type, DateTime) values( 1,'q',2016-44-08 12:44:39.128)
Incorrect syntax error near '12'
Exception thrown: 'System.Data.Odbc.OdbcException' in System.Data.dll
Can someone help me figure out this syntax error?
The datetime values should be withing single quotes. Try this
string strQuery = "INSERT INTO [Order] (Quantity, Type, DateTime)
values( " + qty + "," + type + ",'" + dtstmp.ToString("yyyy-mm-dd hh:mm:ss.fff") + "')";
Actually a simple fix by adding a ' before and after your dateString will not solves your issues, since your query opens a wide door for hackers. I prefer you to use parameterized queries instead for this plain-texts/concatenated strings. obviously that will fix this issue as well; the code for this will be like this:
string strQuery = "INSERT INTO [Order] (Quantity, Type, DateTime)Values( #qty,#type,#date)";
// create and open connection here
using (SqlCommand cmdSQL = new SqlCommand(strQuery))
{
// assign connection for this comnmand
cmdSQL.Parameters.Add("#qty", SqlDbType.Int).Value = qty;
cmdSQL.Parameters.Add("#type", SqlDbType.VarChar).Value = type;
cmdSQL.Parameters.Add("#date", SqlDbType.DateTime).Value = dtstmp;
cmdSQL.ExecuteNonQuery();
}
When i add the lastImportedDate(dd-mm-yyyy) with the following method to the sql server everything is fine. In the database the date is yyyy-mm-dd
But add the lastImportedDate(dd-mm-yyyy) with a different pc on the same server the day and month are switched. In the database the date is yyyy-dd-mm.
internal static void insertSelloutSales(string CustomerID, string type, DateTime lastImported, string periodStart, string periodEnd)
{
// Create SQL connection #connection
SqlConnection sqlConnection1 = new SqlConnection(Connection.connectionString());
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
string periodstartQuery = periodStart;
string periodEndQuery = periodEnd;
// Create query with values and execute query
if (!periodStart.Equals("NULL"))
{
periodstartQuery = " '" + periodStart + "'";
}
if (!periodEnd.Equals("NULL"))
{
periodEndQuery = " '" + periodEnd + "'";
}
cmd.CommandText = "Insert into CarsSellout (CustomerID, type, lastImportedDate, PeriodStart, PeriodEnd) VALUES ('" + CustomerID + "', '" + type + "', '" + lastImported + "', " + periodstartQuery + ", " + periodEndQuery + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
Note that the date settings on the pc's are both set as dd-mm-yyyy.
if you need more info please add a comment.!
What can be the problem in this case?
Do not insert your DateTime values with their string representations. Add your DateTime values directly to your parameterized queries.
SQL Server keeps your DateTime values in a binary format. They didn't have any format or something. What you saw them as yyyy-MM-dd or dd-MM-yyyy are just their textual representations.
Generating different string representations of a DateTime instance for different servers usually because they use different culture settings. But since you didn't show any relevant code that generates your strings, we never know.
Speaking of, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Please read carefully;
Bad habits to kick : choosing the wrong data type
As a best practice, use using statement to dispose your connections and commands automatically instead of calling Close methods manually.
using(var con = new SqlConnection(conString))
using(var cmd = con.CrateCommand())
{
// Define your CommandText with parameterized query.
// Define your parameters and their values. Add them with Add method to your command
// Open your connection
// Execute your query
}
I found some threads here in the forum related to this problem but they didn't help me. I just want to update my database with a date value. These come from a Textfile (written there as 2014-10-02 for example). Now I tried this (which was mentioned in the other threads):
String connectionQuery = form1.conString.Text;
SqlConnection connection = new SqlConnection(connectionQuery);
SqlCommand sqlComInsert = new SqlCommand(#"INSERT INTO [" + form1.tableName.Text + "] ([" + form1.CusId.Text + "],["+ form1.date.Text +"],[" + form1.cusName.Text + "]) VALUES('" + cusId[i] + "',convert(date,'" + date[i] + "',104),'" + "','" + cusName[i] + "')", connection);
sqlComInsert.Connection.Open();
sqlComInsert.ExecuteNonQuery();
sqlComInsert.Connection.Close();
Now when I leave the "'" out ("',convert / "',104)) he tells me that the syntax is incorrect near 2013 (the beginning of my date). When I write it like above then I get:
String or binary data would be truncated.
What is this? I tried also to convert the date with:
for (int i = 0; i < typeDelDate.Count; i++)
{
unFormatedDate = date[i];
formatedDate = unFormatedDate.ToString("dd/MM/yyyy");
dateFormat.Add(formatedDate);
}
but I get still the same errors. How can I update my values? the column type is "date".
Use parametrized queries instead of slapping strings together:
var commandText = "insert (column) values (#dt);";
var cmd = new SqlCommand(commandText, connection);
cmd.Parameters.AddWithValue("dt", DateTime.ParseExact(dateString, "yyyy-MM-dd"));
cmd.ExecuteNonQuery();
Do not pass values into queries by adding strings - if possible, you should always use parameters. It saves you a lot of trouble converting to proper values (different for different locales etc.), it's more secure, and it helps performance.
I Just Keep Having this Error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2014-10-08 19:39:57)' at line 1
public string ObtenerFechaHora()
{
string query = "select CURRENT_TIMESTAMP() as Fecha";
OpenConnection();
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
DateTime e = (DateTime)cmd.ExecuteScalar();
CloseConnection();
return e.ToString("yyyy-MM-dd H:mm:ss");
}
Then i insert ("Fecha" is the DateTime Column)
string query = "INSERT INTO actividad (idTerminal, Proceso, Nombre, Tiempo, Fecha) VALUES('" + idTerminal + "', '" + Proceso + "', '" + Nombre + "', '1,'" + this.ObtenerFechaHora() + ")";
I been used loot of formats and i keep having error, for example:
e.ToString("yyyy-MM-dd H:mm:ss");
e.ToString("yyyy-MM-dd HH:mm:ss");
e.ToString("dd-MM-yyyy H:mm:ss");
e.ToString("yyyy-dd-MMH:mm:ss");
Also with "/" instead of "-"
Any help here?
The problem isn't with the format of the datetime string; the problem is in the SQL text of the INSERT statement, right before the value is appended. For debugging this, you could output the query string and inspect it.
The problem is in the SQL text here:
+ "', '1,'" +
There needs to be a comma between that literal and the next column value. It looks like you just missed a single quote:
+ "', '1','" +
^
A potentially bigger problem is that your code appears to be vulnerable to SQL Injection. Consider what happens when one of the variables you are including into the SQL text includes a single quote, or something even more nefarios ala Little Bobby Tables. http://xkcd.com/327/.
If you want a column value to be the current date and time, you don't need to run a separate query to fetch the value. You could simply reference the function NOW() in your query text. e.g.
+ "', '1', NOW() )";
You excuted twice
//cmd.ExecuteNonQuery();
DateTime e = (DateTime)cmd.ExecuteScalar();
Should be only one time.
Then like #sgeddes said in the comments use parameterized queries, they avoid errors and sql injections.
The approach that you have used is not the best approach to write SQL command. You should use sql parameters in the Query. Your code is vulnerable to SQL Injected and obviously it is not the best approach.
Try using something like this:
string commandText = "UPDATE Sales.Store SET Demographics = #demographics "
+ "WHERE CustomerID = #ID;";
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#ID", SqlDbType.Int);
command.Parameters["#ID"].Value = customerID;
I'm trying to insert a date into a SQL table, but it when the program runs it gives the following error.
Conversion failed when converting date and/or time from character string.
string dateReleased = DateReleasedDate.Value.ToString("YYYY-MM-DD");
string myQuery = "INSERT INTO GameTbl (gameName, genreID, players, online, dateReleased, dateAdded, developerID, publisherID, consoleID) VALUES('"
+ GameNameTxt.Text + "', '" + GenreCombo.SelectedValue + "', '" + PlayersNUD.Value + "', '" + OnlineCombo.SelectedText + "', '"
+ dateReleased + "', 'GETDATE()', '" + DeveloperCombo.SelectedValue + "', '"
+ PublisherCombo.SelectedValue + "','" + ConsoleCombo.SelectedValue + "')";
Please use parametrized queries. My eyes hurt when I see string concatenations used to construct SQL queries:
using (var conn = new SqlConnection("SOME CONNECTION STRING"))
using (var cmd = new SqlCommand(conn))
{
conn.Open();
cmd.CommandText = "INSERT INTO GameTbl (gameName, genreID, players, online, dateReleased, developerID, publisherID, consoleID) VALUES (#gameName, #genreID, #players, #online, #dateReleased, #developerID, #publisherID, #consoleID)";
cmd.Parameters.AddWithValue("#gameName", GameNameTxt.Text);
cmd.Parameters.AddWithValue("#genreID", GenreCombo.SelectedValue);
cmd.Parameters.AddWithValue("#players", PlayersNUD.Value);
cmd.Parameters.AddWithValue("#online", OnlineCombo.SelectedText);
cmd.Parameters.AddWithValue("#dateReleased", DateReleasedDate.Value);
cmd.Parameters.AddWithValue("#developerID", DeveloperCombo.SelectedValue);
cmd.Parameters.AddWithValue("#publisherID", PublisherCombo.SelectedValue);
cmd.Parameters.AddWithValue("#consoleID", ConsoleCombo.SelectedValue);
var result = cmd.ExecuteNonQuery();
...
}
As far as the dateAdded column is concerned I would simply remove it from the INSERT and add it a default value directly in the SQL database.
Notice how you are directly passing DateTime instances and you leave ADO.NET handle the formats. As a bonus your code is safe against SQL injections.
DateReleasedDate.Value.ToString("yyyy-MM-dd");
The problem is you put GETDATE() into single-quotes. It is trying to convert the string 'GETDATE()' into a date.
The best way to pass a date into SQL from .net, IMO, is to use the .ToOADate function.
The function passes in a numerical representation of the date that will work on any database datetime \ date field regardless of the regional setup.
Some info for you: ToOADate