SQL DateTime format error [duplicate] - c#

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();
}

Related

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

Access 2013 syntax error on INSERT INTO statement [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have the following query in c# and don't have any idea why it shows me this error:
"syntax error on INSERT INTO statement".
I use Access 2013.
OleDbCommand command2 = new OleDbCommand();
command2.Connection = connection;
command2.CommandText = "INSERT INTO money (price,cardnum,checknum,dateTime,employeeid) values('" + TempPrice + "','" + TempCriditNum + "','" + TempCheckNum + "','" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "','" + id + "')";
command2.ExecuteNonQuery();
connection.Close();
A few things to check
dateTime is a reserved word. Try wrapping it in square brackets -
if the type of data you are dealing with is a Date\Time then you should be wrapping the input in # signs
if your data types are not strings, do not wrap them in quotes
as pointed out by Jia Jian, you should use parameterized queries
as pointed out by HansUp, Money is also a reserved word, so wrap it in square brackets
So the query ends up looking like :
command2.CommandText = "INSERT INTO [money] (price,cardnum,checknum,[dateTime],employeeid) values(" + TempPrice + "," + TempCriditNum + "," + TempCheckNum + ",#" + dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString() + "#," + id + ")";
Your SQL statement might be prone to SQL injection. Consider using parameterized queries by adding values via the OleDbCommand.Parameters property instead of concatenating it.
An example would be:
command2.CommandText = "INSERT INTO [money] (price, cardnum, checknum, [dateTime], employeeid) values(#tempPrice, #tempCreditNum, #tempCheckNum, #dateTime, #id)";
command2.Parameters.AddRange(new OleDbParameter[] {
new OleDbParameter("#tempPrice", TempPrice),
new OleDbParameter("#tempCreditNum", TempCriditNum),
new OleDbParameter("#tempCheckNum", TempCheckNum),
new OleDbParameter("#dateTime", dateTimePickerX1.GetSelectedDateInPersianDateTime().ToShortDateString()),
new OleDbParameter("#id", id)
});
command2.ExecuteNonQuery();
This should also solve your syntax error.

Insert into DateTime (from C# to MySQL)

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;

C# OLEDB protect apostrophie in query

I try to find a way to protect apostrophie in my query string. I have a value in string format that contain apostrophie and it throw me an error when I tried to insert
ex :
Insert into ["excelApp.worksheetsList.ElementAt(0).Name "$"] " + ([col1], [col2])
values values" + " ('" + val1 + "', '" + val2 + "');")
This is an exemple. here val1 contains "hereIsMy'value".
Thanks for helping me
You should use parametrized queries and you don't have to worry about single quotes in query
using(OleDbConnection cn = new OleDbConnection(GetConnectionString()))
{
cn.Open();
string cmdText = "Insert into [" + excelApp.worksheetsList.ElementAt(0).Name + "$] " +
"([col1], [col2]) values (?, ?)";
OleDbCommand cmd = new OleDbCommand(cmdText, cn)
cmd.Parameters.AddWithValue("#p1", val1);
cmd.Parameters.AddWithValue("#p2", val2);
cmd.ExecuteNonQuery();
}
In this example your command text consist of a single string with placeholders for the parameters value. Then a command object is declared to have that string and two parameters are added at its collection of parameters. They are created according to the variable type passed as value. So, if val1 and val2 are strings and a single quote (apostrophe) is present it is automatically formatted for the insert/delete/update or select operation requested
Use parameterized commands and you won't have to worry about such things. You won't have to worry about apostrophes and a bunch of other problems.

insert date into SQL

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

Categories