I have a birthdate column of type Date in sql database
And in my application I use a dateTimePicker to get the birth date
But when i am trying to insert the date taken from the dateTimePicker:
I get an error :
Incorrect syntax near '12'
And when I try to debug the code I find that the value taken from the dateTimePicker is
Date = {3/21/2015 12:00:00 AM}
The CODE:
//cmd is sql command
cmd.CommandText="INSERT INTO person (birthdate) VALUES("+dateTimePicker.Value.Date+")";
//con is sql connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
What you really should do is use parameters to avoid SQL injection attacks - and it also frees you from string formatting dates - also a good thing!
//cmd is sql command
cmd.CommandText = "INSERT INTO dbo.Person(birthdate) VALUES(#Birthdate);";
cmd.Parameters.Add("#Birthdate", SqlDbType.Date).Value = dateTimePicker.Value.Date;
//con is sql connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Also, it's a recommend best practice to put your SqlConnection, SqlCommand and SqlDataReader into using(....) { .... } blocks to ensure proper disposal:
string connectionString = ".......";
string query = "INSERT INTO dbo.Person(birthdate) VALUES(#Birthdate);";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("#Birthdate", SqlDbType.Date).Value = dateTimePicker.Value.Date;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
As mentioned before the best practice is to use parameters, but if you really need to use a TSQL statement from source you should use date in the format: yyyymmdd
cmd.CommandText="INSERT INTO person (birthdate) VALUES('"+dateTimePicker.Value.Date.ToString("yyyyMMdd")+"')";
Try including quotes:
cmd.CommandText="INSERT INTO person (birthdate) VALUES('"+dateTimePicker.Value.Date+"')";
I'd recommend using parameters too.
Try this as string format:
cmd.CommandText="INSERT INTO person(birthdate)VALUES('"+dateTimePicker.Value.Date+"')";
dateTimePicker stores values as 1/1/1900 12:00:00 AM so you should use DATETIME if you're trying to store it since DATETIME's format is: YYYY-MM-DD HH:MI:SS.
You can print the dateTimePicker value using
MessageBox.Show(dateTimePicker.Value.ToString());
to see for yourself.
Related
I am writing a small app using WPF/C# & SQLITE.
One of the functions inserts a record containing two date/time values into a table.
I want to know if there is a proper way to do this (to ensure that the date/month fields are stored consistently).
I have created an INSERT query that uses parameters alongside date variables (clsVariables.DatActivityEnd = DateTime.Now;).
String cntnStr = ClsVariables.StrDb;
var connection = new SQLiteConnection(cntnStr);
connection.Open();
using (SQLiteCommand cmd = connection.CreateCommand())
{
cmd.CommandText =
"INSERT INTO tblActivity ([Activity_Category], [Activity_Category_Sub], [Activity_Start], [Activity_End], [Activity_Duration]) VALUES (#ActivityCategory, #ActivityCategorySub, #ActivityStart, #ActivityEnd, #ActivityDuration);";
cmd.Parameters.Add(new SQLiteParameter("#ActivityCategory", ClsVariables.StrActivityCurrent));
cmd.Parameters.Add(new SQLiteParameter("#ActivityCategorySub", ClsVariables.StrActivitySubCurrent));
cmd.Parameters.Add(new SQLiteParameter("#ActivityStart", ClsVariables.DatActivityStart.ToString()));
cmd.Parameters.Add(new SQLiteParameter("#ActivityEnd", ClsVariables.DatActivityEnd.ToString()));
cmd.Parameters.Add(new SQLiteParameter("#ActivityDuration", ClsVariables.DblActivityDuration));
cmd.ExecuteNonQuery();
}
connection.Close();
Is there anything else I should do - Thank you?
You have to use sql formatted strings:
string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");
Update:
Today I would prefer AddWithValues with Type Safety and without any Conversion:
cmd.Parameters.AddWithValue("#ActivityStart", ClsVariables.DatActivityStart);
I have a SQL Database with the following structure:
I have 4 MaskedTextBox for:
(Structure)
DateFrom: 0000.00.00
DateFromTime: 00:00:00
DateTo: 0000.00.00
DateToTime: 00:00:00
.
SqlCommand cmd = new SqlCommand("INSERT INTO TABELLE2 (MessageHeadline, MessageText, SpecifyUser, CreateDate, CreateTime, CreateUser, DateFrom, DateFromTime, DateTo, DateToTime) VALUES (#MessageHeadline, #MessageText, #SpecifyUser, #CreateDate, #CreateTime, #CreateUser, #DateFrom, #DateFromTime, #DateTo, #DateToTime)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#MessageHeadline", TB_MSGHeadline.Text);
cmd.Parameters.AddWithValue("#MessageText", TB_MSGText.Text);
cmd.Parameters.AddWithValue("#SpecifyUser", TB_SpecifyUser.Text);
cmd.Parameters.AddWithValue("#CreateDate", CreateDate );
cmd.Parameters.AddWithValue("#CreateTime", CreateTime);
cmd.Parameters.AddWithValue("#CreateUser", CreateUser);
cmd.Parameters.AddWithValue("#DateFrom", MTB_DateFrom.Text);
cmd.Parameters.AddWithValue("#DateFromTime", MTB_DateFromTime.Text);
cmd.Parameters.AddWithValue("#DateTo", MTB_DateTo.Text);
cmd.Parameters.AddWithValue("#DateToTime", MTB_DateToTime.Text);
connection.Open();
cmd.ExecuteNonQuery();
TB_MSGHeadline.Clear();
TB_MSGText.Clear();
TB_SpecifyUser.Clear();
And finally I want to save these values from my MasketTextBox into my database to use them later.
I try to change the Structure and try some SQL Date/Time formation but i get the error:
You're passing the DATE parameters in the incorrect format. You need to pass them as a valid DateTime which your MaskedTextBox values do not appear to be.
For example, #DateFrom is a SQL Date data type. You should pass it a valid parameter such as a DateTime:
cmd.Parameters.AddWithValue("#DateFrom", DateTime.Now);
You may need to parse the MaskedTextBox values correct using DateTime.TryParse
DateTime parsedDate;
bool success = DateTime.TryParse(MaskedInputOne.Text, out parsedDate);
if (success) {
cmd.Parameters.AddWithValue("#DateFrom", parsedDate);
}
In this case we are only adding the parameter if the conversion succeeds.
an error while storing date in DB (SQL server 2005) using C#
I am using,
DateTime mydate = DateTime.Now;
insert into mytablename (appdate) values('"+mydate.ToShortDateString()+"');
bt its showing error when I run the query
also tried,
mydate.ToShortDateString().ToString("dd-MMM-yyyy HH:mm:ss") in C# , still showing error in editor only.
How do I store 'date' in SQL Server 2005 using C# query
Use parameterized SQL, and set the value into the parameter:
string sql = "insert into tablename (appdate) values (#appdate)";
using (var connection = new SqlConnection(...))
{
connection.Open();
using (var command = new SqlCommand(sql, connection))
{
command.Parameters.Add("#appdate", SqlDbType.DateTime).Value
= DateTime.Now;
int rowsInserted = command.ExecuteNonQuery();
// TODO: Validation of result (you'd expect it to be 1)
}
}
You should always use parameterized SQL when you have data to include in the request to the database. This avoids SQL injection attacks and data conversion issues, as well as keeping your code cleaner.
You should also consider whether you really want it to be the local date/time or the UTC date/time. For example, you might want to use DateTime.UtcNow instead.
Your query tries to insert a string in a DateTime field. And of course it doesn't work.
The correct way to insert is through a parametrized query like this
string insertSQL = "insert into mytablename (appdate) values(#dt)";
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#dt", mydate);
cmd.ExecuteNonQuery();
Here I assume that the connection is already initialized and opened
my question looks simple: in my client/server application I want to record a specific date provided by the client.
The problem is that I don't know the regional settings of the client, and I don't know the regional settings of the SQL Server.
How can the client application provide a date in whatever format (last login of a specific user) and store it in a SQL Server table that might be installed with a different regional settings (french, english, italian, german, etc...).
Simple: don't use strings. Use a parameter that is typed as a datetime; can be as simple as:
DateTime when = ...
using(var cmd = conn.CreateCommand()) {
cmd.CommandText = "... #when ...";
cmd.Parameters.AddWithValue("when", when);
cmd.ExecuteNotQuery();
}
or with "dapper":
conn.Execute("... #when ...", new { when });
Dates/times are actually just numbers. It is only when you write/parse it as a string that formatting is an issue.
Just store everything in UTC date in sqlserver. And while retrieving the date convert the utc date to the timezone of the user. I hope users timezone is maintained in your database.
You will need a timezone table and a conversion function that will convert the UTC time to the users local time.
to insert a date in SQL use a string in the form 'YYYYMMDD'
what comes from the client-side you sould know what is it
You should use Parameters, but you also can format date to ISO format by date.ToString("s")
Use datetime format, and store dates as UTC time.
You'll probably also be interested in datetimeoffset.
Validation part
DateTime dt;
string YourDate = "Your Date";
if (DateTime.TryParse(YourDate, out dt))
{
//Your Code
}
Stored Procedure Record Insertion/Retrieval
using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string"))
{
con.Open();
SqlCommand cmd = new SqlCommand();
string expression = "Date Parameter value";
DateTime dt;
if (DateTime.TryParse(expression, out dt))
{
//Your Code
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Your Stored Procedure";
cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression;
cmd.Connection = con;
using (IDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
}
}
}
While storing the data in Sql Server Keep the data format consistent and synchronized with the data format while retrieving....
i cant insert for using c# language DateTime.Now.ToString()
insert sqlserver in datatype datetime field
Don't convert your DateTime value to a string. Use parameterised SQL instead:
string sql = "INSERT INTO Your_Table (Your_Column) VALUES (#YourParam)";
using (SqlConnection conn = new SqlConnection("..."))
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("#YourParam", SqlDbType.DateTime).Value = yourDate;
conn.Open();
cmd.ExecuteNonQuery();
}
You shouldnt have to perform ToString() in order to insert to an SQL server db
Your question didn't make a lot of sense, but I think you're looking for this:
DateTime.Now.ToString(string format)
That'll format the DateTime in the way you want it to.
Yous really shouldn't be building your SQL queries as strings in the first place, though. You should be using parameters, which allow you to give a C# non-string object rather than a converted string.