简体   繁体   中英

DateTime.Now into smalldatetime?

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:

  1. Your date parameter needs to call date.ToString()
  2. 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.

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