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

时间:2011-11-14 05:59:44

标签: c# asp.net sql-server 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 + "'";

地址是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'

我用过

string sql = str.Replace("\'", " ");.

然后我得到

exec sp_cust_reg  C7 , George Joseph , Male , 0001-212123 , jo"hn s house , 515151 , 04862787896 , 8888888888 , johnyqw@gmail.com , N 

3 个答案:

答案 0 :(得分: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();

答案 1 :(得分:1)

您还可以使用Parameterized queries  使用像

这样的参数的AddWithValue()给出值
SqlCommand cmd = new SqlCommand("dbo.sp_cust_reg",_connection);
cmd.CommandType= CommandType.StoredProcedure;

cmd.Parameters.AddWithValue("@TheDate",customer.Cust_Id);
cmd.Parameters.AddWithValue("@Cust_Name",customer.Cust_Name);

_connection.Open();
cmd.ExecuteNonQuery();
_connection.Close();

为什么我告诉使用AddWithValue是 - 你明确设置sqldb.type并且SQL在传递时确切地知道dbtype。

答案 2 :(得分:-1)

您将'转义为''

而不是str.Replace("\'", " ")使用str.Replace("'", "''")

相关问题