Sql Server 2005插入查询中的单引号和双引号

Dav*_*ohn -1 c# sql-server asp.net sql-server-2005

地址文本框中有单引号和双引号.如何插入数据库.我正在使用SQL2005.我的代码如下......

str = "exec sp_cust_reg '" + customer.Cust_Id + "','" + customer.Cust_Name + "','" + customer.Gender + "','" + customer.Acc_no + "','" + customer.Address + "','" + customer.Pin_no + "','" + customer.Phone_no + "','" + customer.Mobile_no + "','" + customer.Email + "','" + customer.Authorise + "'";
Run Code Online (Sandbox Code Playgroud)

地址是jo"hn's house

它的Text Visualizer如下......

exec sp_cust_reg 'C7','George Joseph','Male','0001-212123','jo"hn's house','515151','04862787896','8888888888','johnyqw@gmail.com','N'
Run Code Online (Sandbox Code Playgroud)

我用了

string sql = str.Replace("\'", " ");.
Run Code Online (Sandbox Code Playgroud)

然后我明白了

exec sp_cust_reg  C7 , George Joseph , Male , 0001-212123 , jo"hn s house , 515151 , 04862787896 , 8888888888 , johnyqw@gmail.com , N 
Run Code Online (Sandbox Code Playgroud)

mar*_*c_s 8

一句话:不要做!

使用参数化查询 - 这些更安全(没有SQL注入)并且更容易使用,并且性能也更好!

SqlCommand cmd = new SqlCommand("dbo.sp_cust_reg", _connection);
cmd.CommandType = CommandType.StoredProcedure;

// add parameters and their values
cmd.Parameters.Add("@CustID", SqlDbType.Int).Value = customer.Cust_Id;
cmd.Parameters.Add("@Cust_Name", SqlDbType.VarChar, 100).Value = customer.Cust_Name;
 ..... and so on - define all the parameters!

_connection.Open();
cmd.ExecuteNonQuery();
_connection.Close();
Run Code Online (Sandbox Code Playgroud)

  • @DavidJohn:糟糕的设计......这是一个用于SQL注入的**大范围开放的BARN DOOR**.如果我必须维护这个,我会抛出`Insert`方法并创建一个新的1))要调用的存储过程的名称,以及b)要在调用中使用的`SqlParameter`列表.... (2认同)