[Solved] Error inserting date and time in SQL Server 2005 datetime c#? [closed]


You should ALWAYS use parametrized queries – this prevents SQL injection attacks, is better for performance, and avoids unnecessary conversions of data to strings just to insert it into the database.

Try somethnig like this:

// define your INSERT query as string *WITH PARAMETERS*
string insertStmt = "INSERT into survey_Request1(sur_no, sur_custname, sur_address, sur_emp, sur_date, sur_time, Sur_status) VALUES(@Surname, @SurCustName, @SurAddress, @SurEmp, @SurDate, @SurTime, @SurStatus)";

// put your connection and command into "using" blocks
using(SqlConnection conn = new SqlConnection("-your-connection-string-here-"))
using(SqlCommand cmd = new SqlCommand(insertStmt, conn))
{
    // define parameters and supply values
    cmd.Parameters.AddWithValue("@Surname", textBox9.Text.Trim());
    cmd.Parameters.AddWithValue("@SurCustName", textBox8.Text.Trim());
    cmd.Parameters.AddWithValue("@SurAddress", textBox5.Text.Trim());
    cmd.Parameters.AddWithValue("@SurEmp", textBox1.Text.Trim());
    cmd.Parameters.AddWithValue("@SurDate", dateTimePicker2.Value.Date);
    cmd.Parameters.AddWithValue("@SurTime", dateTimePicker2.Value.Time);
    cmd.Parameters.AddWithValue("@SurStatus", "Active");

    // open connection, execute query, close connection again
    conn.Open();
    int rowsAffected = cmd.ExecuteNonQuery();
    conn.Close();
}

It would also be advisable to name your textboxes with more expressive names. textbox9 doesn’t really tell me which textbox that is – textboxSurname would be MUCH better!

5

solved Error inserting date and time in SQL Server 2005 datetime c#? [closed]