向数据库中添加sql语句

本文关键字:sql 语句 添加 数据库 | 更新日期: 2023-09-27 18:07:05

我必须将SQL语句作为字符串插入数据库,如:

string content = "insert into myTable(content) values ('" + myContent + "')";
string sql = "insert into myTable2(sqlStatement) values ('" + content + "')";

显然这不起作用,因为'content中,所以我添加了以下内容:

Console.WriteLine(content);
content = content.Replace("'", "'''");
Console.WriteLine(content);

我确信变量content已经改变,但仍然有错误与ExecuteNonQuery()

我也试过下面这些,都失败了:

content = content.Replace("'", "''''");
content = content.Replace("'", "'''''");
content = content.Replace("'", @"''");

向数据库中添加sql语句

当您想要转义字符串中的单引号时,不要使用',而是使用双引号。例如,你想插入St. Peter's Chapel,它应该是

string content = "St. Peter''s Chapel"

作为旁注,这不是正确的做法。正确的方法是将值参数化以避免SQL Injection

c#代码片段:
string content = "St. Peter's Chapel"
string connStr = "connection string here";
string sqlStatement = "INSERT INTO tableName (content) VALUES (@content)";
using (SqlConnection conn = new SqlConnection(connStr))
{
    using(SqlCommand comm = new SqlCommand())
    {
        comm.Connection = conn;
        comm.CommandText = sqlStatement;
        comm.CommandType = CommandType.Text;
        comm.Parameters.AddWithValue("@content", content);
        try
        {
            conn.Open();
            comm.ExecuteNonQuery();
        }
        catch(SqlException e)
        {
            // do something with the exception
            // do not hide it
            // e.Message.ToString()
        }
    }
}

正确编码

  • 使用using语句来正确处理对象
  • 使用try-catch块来正确处理对象