简体   繁体   English

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

[英]Single and double quotes in Sql Server 2005 insert query

There is single and double quotes in the address textbox .How can I insert into database. 地址文本框中有单引号和双引号。如何插入数据库。 I am using SQL2005. 我正在使用SQL2005。 My code is as follows... 我的代码如下...

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 + "'";

Address is jo"hn's house 地址是乔恩的家

Its Text Visualizer is as follows... 其文本可视化器如下...

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

I used 我用了

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

Then I get 然后我得到

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

One word: DON'T DO IT! 一句话: 不要做!

Use parametrized queries instead - those are both safer (no SQL injection) and easier to work with, and perform better, too! 改用参数化查询 -既安全(无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();

You can also use Parameterized queries for giving the values, using the AddWithValue() of Parameters like 您还可以使用参数化查询来提供值,并使用Parameters的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();

Why I am telling to use AddWithValue is - you explicitly set the sqldb.type and SQL knows exactly the dbtype when passed. 为什么要告诉我使用AddWithValue是-您显式设置sqldb.type,并且SQL传递时确切知道dbtype。

You escape ' as '' . 你逃跑'''

So instead of str.Replace("\\'", " ") use str.Replace("'", "''") 因此str.Replace("\\'", " ")使用str.Replace("'", "''")代替str.Replace("\\'", " ") str.Replace("'", "''")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM