DateTime.Now into smalldatetime?

2019-08-19 01:47发布

问题:

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..

回答1:

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


回答2:

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.