使用相同的查询但不同的参数查询数据库时,最好是:
使用单个示例:
using (SqlCommand addProduct = new SqlCommand(@"insert into [Products].[Products] ([Name], [Price]) values (@name, @price)", sqlConnection))
{
// Insert the first product.
addProduct.Parameters.AddWithValue("@name", "Product 1");
addProduct.Parameters.AddWithValue("@price", 41F);
int countAffectedRows = addProduct.ExecuteNonQuery();
Debug.Assert(countAffectedRows == 1, "Wrong number of rows affected.");
addProduct.Parameters.Clear();
// Insert the second product.
addProduct.Parameters.AddWithValue("@name", "Product 2");
addProduct.Parameters.AddWithValue("@price", 49.9);
countAffectedRows = addProduct.ExecuteNonQuery();
Debug.Assert(countAffectedRows == 1, "Wrong number of rows affected.");
}
Run Code Online (Sandbox Code Playgroud)
使用两个单独查询的相同代码示例:
// Insert the first product.
using (SqlCommand addProduct = new SqlCommand(@"insert into [Products].[Products] ([Name], [Price]) …Run Code Online (Sandbox Code Playgroud) 初学者:
在我对如何将数据插入SQL Server的问题的答案中,他提到了传递参数而不是像我目前所拥有的字符串连接.
这对安全来说真的有必要吗?如果是这样,究竟是什么传递参数?当我谷歌它我得到很多关于存储过程.这就是我想要的,我不知道存储过程....
如果你能指出我正确的方向,我将不胜感激.
谢谢.
编辑:
好的,这就是我得到的.它似乎正确地更新了数据库,最终我将硬编码的int更改为标签的输入.请确认我是如何做到这一点不容易受到任何SQL注入或攻击.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
public partial class Stats : System.Web.UI.Page
{
public SqlDataReader DataReader;
public SqlCommand Command;
string queryString = ("INSERT INTO UserData (UserProfileID, ConfidenceLevel, LoveLevel, HappinessLevel) VALUES (@UID, @CL, @LL, @HL);");
//string queryString = ("INSERT INTO UserData (UserProfileID, ConfidenceLevel, LoveLevel, HappinessLevel) VALUES ('a051fc1b-4f51-485b-a07d-0f378528974e', 2, 2, 2);");
protected void Page_Load(object sender, EventArgs e)
{ …Run Code Online (Sandbox Code Playgroud)