Datetimepicker 值不能存储在 Access 数据库中
Datetimepicker value cannot be stored in Access Database
我是 MS-Access 和 C# 的新手,我在从 DateTimePicker
向数据库中插入新记录时遇到问题,因为 c# 程序出现以下错误:
Insert into statement is not correct.
所以我想知道:我该如何解决这个问题?
private void btn_insert_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into BP (Name,DateTime,Systolic,Diastolic) VALUES('" + txt_Name.Text + "', '" + dateTimePicker1.Text + "' ," + txt_systolic.Text + "," + txt_diastolic.Text + ");";
command.ExecuteNonQuery();
MessageBox.Show("Changes made Succesfully");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("ERROR " + ex);
}
connection.Close();
}
您必须为日期值传递格式正确的字符串表达式并使用正确的 Access SQL 语法,并且名称是保留字,因此:
command.CommandText = "insert into BP ([Name],DateTime,Systolic,Diastolic) VALUES('" + txt_Name.Text + "', #" + dateTimePicker1.Value.ToString("yyyy'/'MM'/'dd hh':'mm':'ss") + "# ," + txt_systolic.Text + "," + txt_diastolic.Text + ");";
我是 MS-Access 和 C# 的新手,我在从 DateTimePicker
向数据库中插入新记录时遇到问题,因为 c# 程序出现以下错误:
Insert into statement is not correct.
所以我想知道:我该如何解决这个问题?
private void btn_insert_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "insert into BP (Name,DateTime,Systolic,Diastolic) VALUES('" + txt_Name.Text + "', '" + dateTimePicker1.Text + "' ," + txt_systolic.Text + "," + txt_diastolic.Text + ");";
command.ExecuteNonQuery();
MessageBox.Show("Changes made Succesfully");
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("ERROR " + ex);
}
connection.Close();
}
您必须为日期值传递格式正确的字符串表达式并使用正确的 Access SQL 语法,并且名称是保留字,因此:
command.CommandText = "insert into BP ([Name],DateTime,Systolic,Diastolic) VALUES('" + txt_Name.Text + "', #" + dateTimePicker1.Value.ToString("yyyy'/'MM'/'dd hh':'mm':'ss") + "# ," + txt_systolic.Text + "," + txt_diastolic.Text + ");";