我是新手,目前我的代码部分出现问题,单击数据库中的按钮后会出现语法错误。
private void button1_Click(object sender, EventArgs e)
{
FlightConn.Open();
oleDbCmd.Connection = FlightConn;
oleDbCmd.CommandText = "insert into tbl_flight (fld_PassengerName, fld_destination, fld_class, fld_date, fld_time) ('" +
this.textBox1.Text + "', '" + this.textBox2.Text + "', '" + this.comboBox1.SelectedItem + "', '" + this.comboBox2.SelectedItem + "','" + this.dateTimePicker1.Value + "');";
int temp = oleDbCmd.ExecuteNonQuery();
if (temp > 0)
{
textBox1.Text = null;
textBox2.Text = null;
comboBox1.Text = null;
comboBox2.Text = null;
dateTimePicker1.Text = null;
MessageBox.Show("Record Successfully Added");
}
else
{
MessageBox.Show("Record Failed to Add");
}
FlightConn.Close();
}
任何想法是什么问题?谢谢你的任何未来答案
答案 0 :(得分:1)
您插入的查询缺少Values关键字。 Insert into tablename(field1,field2) values(value1,value2)
答案 1 :(得分:1)
您的SQL命令缺少一个子句。您还应该使用参数化查询,而不是将纯文本值输入到查询中。它使查询更安全,因为您不必担心SQL注入。
改变这个:
oleDbCmd.CommandText = "insert into tbl_flight (fld_PassengerName, fld_destination, fld_class, fld_date, fld_time) ('" +
this.textBox1.Text + "', '" + this.textBox2.Text + "', '" + this.comboBox1.SelectedItem + "', '" + this.comboBox2.SelectedItem + "','" + this.dateTimePicker1.Value + "');";
更像这样的事情:
oleDbCmd.CommandText = "insert into tbl_flight(fld_PassengerName, fld_destination, fld_class, fld_date, fld_time) values(@PassengerName, @Destination, @Class, @Date, @Time)";
List<OleDbParameter> args = new List<OleDbParameter>();
args.Add(new OleDbParameter("@PassengerName", textBox1.Text));
args.Add(new OleDbParameter("@Destination", textBox2.Text));
args.Add(new OleDbParameter("@Class", comboBox1.SelectedItem));
args.Add(new OleDbParameter("@Date", comboBox2.SelectedItem));
args.Add(new OleDbParameter("@Time", dateTimePicker1.Value));
oleDbCmd.Parameters.Add(args.ToArray());
答案 2 :(得分:0)
您错过了指定“值”关键字..试试这个
oleDbCmd.CommandText = "insert into tbl_flight (fld_PassengerName, fld_destination, fld_class, fld_date, fld_time) values('" +
this.textBox1.Text + "', '" + this.textBox2.Text + "', '" + this.comboBox1.SelectedItem + "', '" + this.comboBox2.SelectedItem + "','" + this.dateTimePicker1.Value + "');";
答案 3 :(得分:0)
您的sql语句中似乎缺少&#34; VALUES&#34; 关键字
答案 4 :(得分:0)
你的sql字符串必须是;
string.Format(@"INSERT INTO tbl_flight (fld_PassengerName, fld_destination, fld_class, fld_date, fld_time)
VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}');",
this.textBox1.Text, this.textBox2.Text, this.comboBox1.SelectedItem,
this.comboBox2.SelectedItem, this.dateTimePicker1.Value);