Single and double quotes in Sql Server 2005 insert query

后端 未结 3 987
猫巷女王i
猫巷女王i 2021-01-29 08:48

There is single and double quotes in the address textbox .How can I insert into database. I am using SQL2005. My code is as follows...

str = \"exec sp_cust_reg \         


        
相关标签:
3条回答
  • 2021-01-29 09:34

    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!

    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();
    
    0 讨论(0)
  • 2021-01-29 09:41

    You escape ' as ''.

    So instead of str.Replace("\'", " ") use str.Replace("'", "''")

    0 讨论(0)
  • 2021-01-29 09:42

    You can also use Parameterized queries for giving the values, using the AddWithValue() of Parameters like

    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.

    0 讨论(0)
提交回复
热议问题