winforms 如何插入数据库的特定列

xt0899hw  于 2022-12-04  发布在  其他
关注(0)|答案(1)|浏览(154)

问题是当我尝试插入时,我收到一个异常错误,指出外部数据库中的数据不匹配
我有一个客户预订表,其中预订ID ...pk作为自动编号,客户.... fk和日期作为日期时间预订ID是自动递增的,因此我不需要插入任何内容
我想要实现的是插入customer_id和date,但我一直得到数据不匹配,并且查询值的数量与目标字段不同
那么,怎样才能正确地表达

using (OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString())) {
    OleDbCommand cmd = new OleDbCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "insert into customer_booking  ([customer_id],[date_in]) values (?,?)";
    cmd.Parameters.AddWithValue("@customer_id", txtusername.Text);
    cmd.Parameters.AddWithValue("@date_in", dtdate_in);
    cmd.Connection = myCon;
    myCon.Open();
    cmd.ExecuteNonQuery();
    System.Windows.Forms.MessageBox.Show("your booking was successful ", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
tez616oj

tez616oj1#

使用cmd.Parameters.add('...')方法,如下所示:

using (OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString())) {
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into customer_booking  ([customer_id],[date_in]) values (@customer_id,@date_in)";
///* Set your column dataType*/
cmd.Parameters.Add("@customer_id", SqlDbType.VarChar , 50).Value = txtusername.Text; 
cmd.Parameters.Add("@date_in", SqlDbType.DateTime).Value = dtdate_in; 
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
    System.Windows.Forms.MessageBox.Show("your booking was successful ", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}

相关问题