using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-O72COGQ;Initial Catalog=ClinicManagementtest;Integrated Security=True"))
{
con.Open();
SqlCommand sc = new SqlCommand("INSERT INTO Patient_Details VALUES(@Id, @Name, @Age, @Contact No, @Address", con);
sc.Parameters.AddWithValue("@Id", textBox1.Text);
sc.Parameters.AddWithValue("@Name", textBox2.Text);
sc.Parameters.AddWithValue("@Contact No", textBox3.Text);
sc.Parameters.AddWithValue("@Address", textBox5.Text);
int o = sc.ExecuteNonQuery();
MessageBox.Show(o + ":Record has been inserted");
con.Close();
}
答案 0 :(得分:0)
你在这里犯了很多错误。
所以,让我们试着尽我们所知来解决问题
string cmdText = @"INSERT INTO Patient_Details
(ID, Name, Age, Gender, [Contact No], Address)
VALUES(@Id,@Name,@Age,@Gender,@ContactNo, @Address)"
using (SqlConnection con = new SqlConnection(....))
{
con.Open();
SqlCommand sc = new SqlCommand(cmdText, con);
sc.Parameters.AddWithValue("@Id", textBox1.Text);
sc.Parameters.AddWithValue("@Name", textBox2.Text);
// For the following two fields, add a value or remove
// the parameters and fix the query text above....
sc.Parameters.AddWithValue("@age", ????);
sc.Parameters.AddWithValue("@gender", ????);
sc.Parameters.AddWithValue("@ContactNo", textBox3.Text);
sc.Parameters.AddWithValue("@Address", textBox5.Text);
int o = sc.ExecuteNonQuery();
MessageBox.Show(o + ":Record has been inserted");
}
答案 1 :(得分:-1)
就像Sankar Raj指出你错过了)
查询中的Insert
和要添加的参数@Age
。也不允许在参数@Contact No
中使用空格。
您已使用using
SqlConnection
。我建议您同样使用SqlCommand
,然后您不需要明确Dispose
它。而且似乎你没有使用try catch
那是你无法识别问题的。
建议代码
try{
using (SqlConnection con = new SqlConnection("Data Source=DESKTOP-O72COGQ;Initial Catalog=ClinicManagementtest;Integrated Security=True"))
{
con.Open();
using (SqlCommand sc = new SqlCommand("INSERT INTO Patient_Details VALUES(@Id, @Name, @Age,@Gender, @ContactNo, @Address)", con)){
sc.Parameters.AddWithValue("@Id", textBox1.Text);
sc.Parameters.AddWithValue("@Name", textBox2.Text);
sc.Parameters.AddWithValue("@Gender", textBox3.Text);
sc.Parameters.AddWithValue("@ContactNo", textBox4.Text);
sc.Parameters.AddWithValue("@Age", textBox5.Text);
sc.Parameters.AddWithValue("@Address", textBox6.Text);
int o = sc.ExecuteNonQuery();
MessageBox.Show(o + ":Record has been inserted");
}
}
}catch(Exception ex){
MessageBox.Show(ex.Message);
}
注意:我已删除con.Close()
。由于您使用的是using
语句,因此会自动Close
& Dispose
连接并释放它使用的资源。