数据未插入数据库表

本文关键字:数据库 插入 数据 | 更新日期: 2023-09-27 18:27:38

string constr = "Data Source =. ;Initial Catalog =reg ;Integrated Security=true;";
SqlConnection conn = new SqlConnection(constr);
conn.Open();
string sql = "Insert Into Course Values(@CustomerFName,@CustomerLName,@Email ,@PhoneNo ,@CourseName);";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@CustomerFName", txthrfn.Text);
cmd.Parameters.AddWithValue("@CustomerLName", txthrln.Text);
cmd.Parameters.AddWithValue("@Email", txthrem.Text);
cmd.Parameters.AddWithValue("@PhoneNo", txthrmob.Text);
cmd.Parameters.AddWithValue("@CourseName", ddlhr.SelectedItem.ToString());
cmd.ExecuteNonQuery();
conn.Close();

数据未插入数据库表

我会尝试这样的东西:

    string constr = "Data Source =. ;Initial Catalog =reg ;Integrated Security=true;";
    SqlConnection conn = new SqlConnection(constr);
    try
    {
        conn.Open();
    }
    catch (Exception err)
    { MessageBox.Show(err.Message); }
    string sql = "Insert Into Course(CustomerFName,CustomerLName,Email,PhoneNo,CourseName) Values(@CustomerFName,@CustomerLName,@Email,@PhoneNo,@CourseName)";
    SqlCommand cmd = new SqlCommand(sql, conn);
    cmd.Parameters.AddWithValue("@CustomerFName", txthrfn.Text);
    cmd.Parameters.AddWithValue("@CustomerLName", txthrln.Text);
    cmd.Parameters.AddWithValue("@Email", txthrem.Text);
    cmd.Parameters.AddWithValue("@PhoneNo", txthrmob.Text);
    cmd.Parameters.AddWithValue("@CourseName", ddlhr.SelectedItem.ToString());
    try { cmd.ExecuteNonQuery(); }
    catch (Exception err)
    { MessageBox.Show(err.Message); }
    try { conn.Close(); }
    catch (Exception err)
    { MessageBox.Show(err.Message); }

至少这样你就会知道出了什么问题。

注意:还不能评论你的问题(没有足够的代表)。