我很擅长使用数据库.现在我可以写SELECT,UPDATE,DELETE,和INSERT命令.但我看过很多我们喜欢写的论坛:
SELECT empSalary from employee where salary = @salary
Run Code Online (Sandbox Code Playgroud)
...代替:
SELECT empSalary from employee where salary = txtSalary.Text
Run Code Online (Sandbox Code Playgroud)
为什么我们总是喜欢使用参数以及如何使用它们?
我想知道第一种方法的用途和好处.我甚至听说过SQL注入,但我并不完全理解它.我甚至不知道SQL注入是否与我的问题有关.
我看到在大多数样本中,SqlCommand都是这样使用的
using (SqlConnection con = new SqlConnection(CNN_STRING))
{
using (SqlCommand cmd = new SqlCommand("Select ID,Name From Person", con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
Run Code Online (Sandbox Code Playgroud)
我知道为什么我们使用"使用"声明.但是SqlCommand没有包含Close()方法,所以我们应该在using语句中使用它
我想创建一个将记录添加到数据库的SQL命令。我尝试了以下代码,但似乎无法正常工作:
SqlCommand comand = new SqlCommand("INSERT INTO Product_table Values(@Product_Name,@Product_Price,@Product_Profit,@p)", connect);
SqlParameter ppar = new SqlParameter();
ppar.ParameterName = "@Product_Name";
ppar.Value = textBox1.Text;
MessageBox.Show("Done");
comaand.Parameters.Add(ppar);
Run Code Online (Sandbox Code Playgroud)