Im trying to get the date and the time using C# , and then insert it into a smalldatetime data type in SQL SERVER.
This is how I try to do it :
DateTime date = DateTime.Now;
sql = "INSERT INTO YTOODLE_LINKS (YTOODLE_LINKS.TASK_ID,YTOODLE_LINKS.LINK_TITLE,YTOODLE_LINKS.LINK_DESC,YTOODLE_LINKS.LINK_PATH,YTOODLE_LINKS.USER_ID,YTOODLE_LINKS.LAST_USER_EDIT)VALUES (1,'','','',2,'1',"+ date +")";
dataObj = new DataObj();
dataObj.InsertCommand(sql);
connection = new SqlConnection(conn);
connection.Open();
cmd = new SqlCommand(sql, connection);
cmd.ExecuteNonQuery();
connection.Close();
and then then it gives me : "Incorrect syntax near '16'."
I guess it refers to my current time , which is 16:15 right now..
I would suggest using parameters. cmd.Parameters.AddWithValue("#date", date.toString); The AddWithField will take care of the proper conversion.
Your InsertSQL statment becomes:
sql = "INSERT INTO YTOODLE_LINKS (YTOODLE_LINKS.TASK_ID,YTOODLE_LINKS.LINK_TITLE,YTOODLE_LINKS.LINK_DESC,YTOODLE_LINKS.LINK_PATH,YTOODLE_LINKS.USER_ID,YTOODLE_LINKS.LAST_USER_EDIT)VALUES (1,'','','',2,'1',#date)";
It doesn't work for 2 reasons:
Your date parameter needs to call date.ToString()
You must add single quotes before and after the date string is inserted in your inline query as so:
sql = "INSERT INTO YTOODLE_LINKS (YTOODLE_LINKS.TASK_ID,YTOODLE_LINKS.LINK_TITLE,YTOODLE_LINKS.LINK_DESC,
YTOODLE_LINKS.LINK_PATH,YTOODLE_LINKS.USER_ID,YTOODLE_LINKS.LAST_USER_EDIT)
VALUES (1,'','','',2,'1','"+ date +"')";
But the above strategy is not good because it exposes you to SQL Injection attacks by concatenating strings the way you are doing it and also because you have to worry about adding single quotes, etc., etc.
A better approach is to use parameters as so:
sql = "INSERT INTO YTOODLE_LINKS (YTOODLE_LINKS.TASK_ID,YTOODLE_LINKS.LINK_TITLE,YTOODLE_LINKS.LINK_DESC,
YTOODLE_LINKS.LINK_PATH,YTOODLE_LINKS.USER_ID,YTOODLE_LINKS.LAST_USER_EDIT)
VALUES (#First,#Second,#Third,#Fourth,#Fifth,#Sixth,#YourDate)";
cmd.Parameters.AddWithValue("#First", 1);
// ... and so on
cmd.Parameters.AddWithValue("#YourDate", date);
Now you don't have to worry about sql injection attacks or adding single quotes to some parameters depending on the data type, etc. It's all transparent to you, you are safer and the database engine will be able to optimize the execution plan for your query.
Related
I have a C# program and I want to run a MySQL query that insert a record. In this record I have a timestamp field that MUST BE the server timestamp, not the client timestamp.
So, I write this:
start_session = new MySqlDataAdapter("INSERT INTO CUBE_WORKTIME(ID_WORKTIME,
ID_RISORSA_FK,DATA,ORA_INIZIO_EVENTO, ORA_FINE_EVENTO,
ID_CDC_FK, CAUSALE, LAST_EVENT)
VALUES ('', '"+ idrisorsa_global + "', DATE(NOW()),NOW(),
NULL, '"+ IDCDC +"', 'Login', 'Y')", connection);
DataTable start_session_dataset = new DataTable();
start_session.Fill(start_session_dataset);
This query works well, the ID_RISORSA_FK and IDCDC fields are correct. But the date and the datetime are 0000-00-00 and 0000-00-00 00:00:00.
I also tried adding the quotes, but no effects.
Any ideas?
The first thing to change is the use of an MySqlDataAdapter to just insert a record. While this could work it is not the correct class to use for this work. A simple MySqlCommand is the correct object to use and with a lot less of infrastructure required
The second thing to change is the way in which you build your sql query. Do not concatenate together strings to form an sql command but use Parameters. This avoid Sql Injection and parsing problems.
So your code could be rewritten as
string cmdText = #"INSERT INTO CUBE_WORKTIME
(ID_RISORSA_FK,DATA,ORA_INIZIO_EVENTO, ORA_FINE_EVENTO,ID_CDC_FK,
CAUSALE, LAST_EVENT) VALUES (#risorsaID, CURDATE(), CURTIME(),
NULL, #cdcID, 'Login', 'Y')";
MySqlCommand cmd = new MySqlCommand(cmdText, connection);
cmd.Parameters.Add("#risorsaID", MySqlDbType.Int32).Value = idrisorsa_global;
cmd.Parameters.Add("#cdcID", MySqlDbType.Int32).Value = IDCDC;
int rowsInserted = cmd.ExecuteNonQuery();
Hello i try to delete from a Table where i need to access a varchar note field and an datetimefield.
Here is the Code:
DateTime test = (DateTime)powerPlant.timestamp;
string DateUS = test.ToString("s");
string deletePowerPlant =
String.Format(
"DELETE FROM [dbo].[tblSPpowerPlants] WHERE [timestamp] = CONVERT(datetime,"+ DateUS +",111) AND [note] = {0};",
note);
SqlCommand sqlDelete = new SqlCommand(deleteComponents, sqlConnection);
sqlDeletePowerPlant.CommandType = CommandType.Text;
sqlDeletePowerPlant.CommandText = deleteComponents;
sqlDeletePowerPlant.ExecuteNonQuery();
And yes normally i would use sql parameters but i want to know how it would work without parameters just to test it out becouse somehow it must be possible. I tried to google it and with some other forum and some blogs but had no luck.
Thx for your help and sorry for my english.
EDIT
The Field timestamp is a Datetime in the table.
The note is a nvarchar in the Table. And i just want to use it once so i can say i know how to do it without parameters. I know its bad....
You'll want to make sure there is no dependency on server operating system locale. So if you use a certain format (111 in your case) in the SQL query, you should use the .NET equivalent to convert your date to a string:
string DateUS = test.ToString("yyyy/MM/dd");
For details about the formats that the CONVERT function supports, see here:
https://msdn.microsoft.com/de-de/library/ms187928(v=sql.120).aspx
As you stated yourself in the question, using a (strongly typed) SqlParameter is the preferred way to go. Failing to so so may result in sql injection vulnerabilities.
Given that note is a text column, single quotes and escaping will be required:
String.Format(
"DELETE FROM [dbo].[tblSPpowerPlants] WHERE [timestamp]=CONVERT(datetime,'{0}',111) AND [note]='{1}'",
DateUS
note.Replace("'","''").Replace(#"\",#"\\")
);
If you store time-of-day too, the comparison with = will not affect records with nonzero time component.
Put some string qualifiers in there
DateTime test = (DateTime)powerPlant.timestamp;
string DateUS = test.ToString("s");
string deletePowerPlant = String.Format("DELETE FROM [dbo].[tblSPpowerPlants] WHERE [timestamp] = CONVERT(datetime,'"+ DateUS +"',111) AND [note] = '{0}';", note);
SqlCommand sqlDelete = new SqlCommand(deleteComponents, sqlConnection);
sqlDeletePowerPlant.CommandType = CommandType.Text;
sqlDeletePowerPlant.CommandText = deleteComponents;
sqlDeletePowerPlant.ExecuteNonQuery();
But really. Use parameterized queries
I have the statement in c# :
String sql = String.Format("UPDATE Table SET FIRST_NAME='{0}',LAST_NAME='{1}',BIRTH_DATE='{2}' where CUSTOMER_NUMBER ='{3}'",FirstName, LastName,DateOfBirth,Number);
The above statement doesn't execute if the first name,last name etc have apostrophe like O'Hare,O'Callahagan because of this the update statement gets the wrong syntax.
How to escape the apostrophe in string.format?
How to escape the apostrophe in string.format?
Don't escape it, use parameterized query instead.
Imagine a user with a really unconventional name strongly resembling SQL statements for dropping a table or doing something equally malicious. Escaping quotes is not going to be of much help.
Use this query instead:
String sql = #"UPDATE Table
SET FIRST_NAME=#FirstName
, LAST_NAME=#LastName
, BIRTH_DATE=#BirthDate
WHERE CUSTOMER_NUMBER =#CustomerNumber";
After that, set values of FirstName, LastName, DateOfBirth, and Number on the corresponding parameters:
SqlCommand command = new SqlCommand(sql, conn);
command.Parameters.AddWithValue("#FirstName", FirstName);
command.Parameters.AddWithValue("#LastName", LastName);
command.Parameters.AddWithValue("#BirthDate", BirthDate);
command.Parameters.AddWithValue("#CustomerNumber", CustomerNumber);
Your RDMBS driver will do everything else for you, protecting you from malicious exploits. As an added benefit, it would let you avoid issues when the date format of your RDBMS is different from your computer: since your date would no longer be passed as a string representation, there would be no issues understanding which part of the formatted date represents a day, and which one represents a month.
You should use parameterized queries:
using (SqlCommand cmd = new SqlCommand("UPDATE Table SET FIRST_NAME= #FirstName, LAST_NAME= #LastName, BIRTH_DATE=#BirthDate where CUSTOMER_NUMBER = #CustomerNumber"))
{
cmd.Parameters.Add(new SqlParameter("FirstName", FirstName));
cmd.Parameters.Add(new SqlParameter("LastName", LastName));
cmd.Parameters.Add(new SqlParameter("BirthDate", DateOfBirth));
cmd.Parameters.Add(new SqlParameter("CustomerNumber", Number));
// Now, update your database
} // the SqlCommand gets disposed, because you use the 'using' statement
By using parameterized queries, you solve your problem. Using parameterized queries has two other advantages:
Protection against SQL Injection
Readability
Use parameterized query.
string commandString = "insert into MyTable values (#val1, #val2)";
SqlCommand command = new SqlCommand(commandString, connection);
command.Parameters.AddWithValue("val1", "O'Hare");
command.Parameters.AddWithValue("val2", "O'Callahagan");
command.ExecuteNonQuery();
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
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.