int =sc.executenonquery();在'附近给出错误&;语法不正确;& # 39;system.d
本文关键字:语法 错误 出错 不正确 system executenonquery sc int | 更新日期: 2023-09-27 18:04:21
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con=new SqlConnection ("Data Source=SAGAR''SQLEXPRESS;Initial Catalog=ClinicDb;Integrated Security=True");
con .Open();
SqlCommand sc=new SqlCommand ("insert into Patient_Details values('"+textBox1 +",'"+textBox2 +",'"+textBox3 +",'"+textBox4 +",'"+textBox5 +");",con );
int o = sc.ExecuteNonQuery();
try
{
if (textBox1.Text.Length == 0 || textBox2.Text.Length == 0 || textBox3.Text.Length == 0 || textBox4.Text.Length == 0 || textBox5.Text.Length == 0)
MessageBox.Show("Fill all the fields");
else
MessageBox.Show("Values are Inserted successfully...!");
textBox1.Clear();
textBox2.Clear();
textBox3.Clear();
textBox4.Clear();
textBox5.Clear();
}
catch (Exception) { MessageBox.Show("something went wrong...Try Again"); }
MessageBox.Show(o + "saved");
con.Close();
}
这里缺少一个撇号:
'"+textBox2 +"
但是不要使用字符串连接来构建查询,而是使用参数化查询。否则,您将打开SQL注入。
还使用using
语句来处置任何非托管资源/关闭连接。
using (var con = new SqlConnection("Data Source=SAGAR''SQLEXPRESS;Initial Catalog=ClinicDb;Integrated Security=True"))
{
con.Open();
using (var sc = new SqlCommand("insert into Patient_Details values(@col1,@col2,@col3,@col4);", con))
{
sc.Parameters.Add("@Col1", SqlDbType.VarChar).Value = textBox1.Text;
sc.Parameters.Add("@Col2", SqlDbType.Int).Value = int.Parse(textBox2.Text);
// ..
int o = sc.ExecuteNonQuery();
// ...
}
}
首先使用正确的数据类型,我已经展示了varchar
和int
的示例。
您缺少textBox1
等结尾的.Text
,并且您没有正确引用项目(您缺少大量'
)。变化:
SqlCommand sc=new SqlCommand ("insert into Patient_Details values('"+textBox1 +",'"+textBox2 +",'"+textBox3 +",'"+textBox4 +",'"+textBox5 +");",con );
:
SqlCommand sc=new SqlCommand ("insert into Patient_Details values('"+ textBox1.Text +"','"+ textBox2.Text +"','"+ textBox3.Text +"','"+ textBox4.Text +"','"+ textBox5.Text +"');",con );
然后,转到http://www.w3schools.com/sql/sql_injection.asp并了解SQL注入攻击并更改代码以防止这种情况发生。关于如何做到这一点,可以参考这个问题。
使用文本框的Text属性
textbox1.Text// in the query.
SqlCommand sc=new SqlCommand ("insert into Patient_Details values('"+textBox1.Text +"','"+textBox2.Text +"','"+textBox3.Text +"','"+textBox4.Text +"','"+textBox5.Text +"');",con );
and of course the missing apostrphe and use parametrized query.