简体   繁体   中英

How to store DateTime of .net in sql server 2008 R2

I am new to .net and sql. I am trying to store the DateTime into database but i am getting exception as "Incorrect syntax near '11' " at 11:21:57 AM i run my code so, i am getting error at time. This is my code for storing into database. Below method will return a query.

    public string InsertADData(string strdateLogin, string strdateLogout, string strName, string strUsername)
    {
        DateTime dateLogin = Convert.ToDateTime(strdateLogin);
        DateTime dateLogout = Convert.ToDateTime(strdateLogout);
        return string.Format(@"INSERT INTO ADTimeData (LoginDate, LogoutDate,name,username) 
                               VALUES ({0},{1},'{2}','{3}')", dateLogin,
                                                            dateLogout,
                                                            strName.Replace("'", "''"),
                                                           strUsername.Replace("'", "''"));
    }

This method is for insert the records into database. Here CheckDBConnection() will open sql connection.

       public void InsertRecords(String strQuery)
        {
            CheckDBConnection();
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = _con;
                cmd.CommandText = strQuery;
                cmd.CommandType = CommandType.Text;
                cmd.ExecuteNonQuery();
            }
        }

When i debug the code which i have written i am getting query ie sqlQuery value Like this

      INSERT INTO ADTimeData (LoginDate, LogoutDate,name,username) 
                              VALUES (1/4/2013 11:21:57 AM,1/4/2013 11:21:57 AM,'raivnder','ravinder.g@gmail.com')

But i am getting exception at

cmd.ExecuteNonQuery();

The exception is shown in below image. 在此输入图像描述

Please help me.

In short: The issue is in datetime format that you are passing in insert statement.

It should be done through a parametrized query. Something similare to the following sample query:

SqlCommand cmd = new SqlCommand("INSERT INTO <table> (<column>) VALUES (@value)", connection);
cmd.Parameters.AddWithValue("@value", dateTimeVariable);

cmd.ExecuteNonQuery();

By all means - use parametrized queries to avoid SQL injection attacks (and to speed up performance, too!):

public string InsertADData(string strdateLogin, string strdateLogout, string strName, string strUsername)
{
    DateTime dateLogin = Convert.ToDateTime(strdateLogin);
    DateTime dateLogout = Convert.ToDateTime(strdateLogout);

    string query = @"INSERT INTO ADTimeData (LoginDate, LogoutDate,name,username) 
                     VALUES (@LoginDate, @LogoutDate, @name, @username)";

    using (SqlConnection conn = new SqlConnection(.....))
    using (SqlCommand cmd = new SqlCommand(query, conn))
    {
        cmd.Parameters.Add("@LoginDate", SqlDbType.DateTime).Value = dateLogin;           
        cmd.Parameters.Add("@LogoutDate", SqlDbType.DateTime).Value = dateLogout;
        cmd.Parameters.Add("@Name", SqlDbType.VarChar, 50).Value = name;
        cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 50).Value = username;

        conn.Open();
        cmd.ExecuteQuery();
        conn.Close(); 
    }

Never concatenate together your SQL statement with the values! This is a really really horribly bad practice - stop doing that. You should always use parametrized queries - no exception

public string InsertADData(string strdateLogin, string strdateLogout, string strName, string strUsername)
{
    DateTime dateLogin = Convert.ToDateTime(strdateLogin);
    DateTime dateLogout = Convert.ToDateTime(strdateLogout);
    return string.Format(@"INSERT INTO ADTimeData (LoginDate, LogoutDate,name,username) 
                           VALUES ('{0}','{1}','{2}','{3}')", dateLogin,
                                                        dateLogout,
                                                        strName.Replace("'", "''"),
                                                       strUsername.Replace("'", "''"));
}

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