I'm trying to insert a datetime value into my database table, but I'm ancountring a problem.
Each time I try to do this, this message pops up:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
This is my code:
public static void DoQuery(string fileName, string sql)
{
SqlConnection conn = ConnectToDb(fileName);
conn.Open();
SqlCommand com = new SqlCommand(sql, conn);
com.ExecuteNonQuery();
com.Dispose();
conn.Close();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection();
cn.ConnectionString = @"Data Source=.SQLEXPRESS;AttachDbFilename='c:users******visual studio 2010Projects******Database.mdf';Integrated Security=True;User Instance=True";
cn.Open();
string[] dateArr = dateBox.Text.Split('/');
int[] dateInt = new int[3];
for (int i = 0; i < 3; i++)
{
dateInt[i] = Int16.Parse(dateArr[i]);
MessageBox.Show(dateInt[i]+"");
}
DateTime date = new DateTime(dateInt[2],dateInt[1],dateInt[0]);
string sql = "INSERT INTO existProducts(name,date,price,amount) VALUES ('" + nameBox.Text + "','" + date + "','" + priceBox.Text + "','" + amountBox.Text + "')";
MyAdoHelper.DoQuery("Database.mdf", sql);
MessageBox.Show("Success!");
cn.Close();
}
Note 1: I had an exeption handling but I removed it because I always had
to handle this exception and the program didn't run well.
Note 2: I censored the connection string, but there is a connection and it works fine.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…