What you really should do is use parameters to avoid SQL injection attacks - and it also frees you from string formatting dates - also a good thing!
//cmd is sql command
cmd.CommandText = "INSERT INTO dbo.Person(birthdate) VALUES(@Birthdate);";
cmd.Parameters.Add("@Birthdate", SqlDbType.Date).Value = dateTimePicker.Value.Date;
//con is sql connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Also, it's a recommend best practice to put your SqlConnection
, SqlCommand
and SqlDataReader
into using(....) { .... }
blocks to ensure proper disposal:
string connectionString = ".......";
string query = "INSERT INTO dbo.Person(birthdate) VALUES(@Birthdate);";
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.Add("@Birthdate", SqlDbType.Date).Value = dateTimePicker.Value.Date;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…