为什么我的代码没有在数据库表中插入记录?

时间:2018-10-27 08:54:05

标签: c# sql .net sql-server sql-insert

我想在Patient表中插入一些数据。但这不是插入。

private void btn_id_Click(object sender, EventArgs e)
{
    int Id=int.Parse(txt_id4.Text);
    string name = Txt_id1.Text;
    string age = txt_id2.Text;
    SqlConnection conn = new SqlConnection();
    SqlCommand cmd = new SqlCommand();
    conn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\best.mdf;Integrated Security=True;User Instance=True";
    cmd.Connection = conn;
    cmd.CommandType = CommandType.Text;               
    conn.Open();
    cmd.CommandText = @"INSERT INTO Patient (Name, Age)Values( @name, @age)";
    cmd.Parameters.AddWithValue("@Id",Id);
    cmd.Parameters.AddWithValue("@name", name);
    cmd.Parameters.AddWithValue("@age", age);
    //Id = Convert.ToInt32(cmd.ExecuteScalar());
    // cmd.Parameters.Add("@Id", Id.ToString)
    cmd.ExecuteNonQuery();
    MessageBox.Show("Data is added");
}

0 个答案:

没有答案