【问题标题】:SQLite Inserts - How to Insert Any Text while Avoiding Syntax Errors using Parameterized ValuesSQLite 插入 - 如何在使用参数化值避免语法错误的同时插入任何文本
【发布时间】:2019-03-09 05:50:57
【问题描述】:

我很想知道将文本字符串插入数据库的正确方法,而不管字符串中包含哪些字符。我的意思是,如果我有一个字符串,例如,它包含单引号或任何其他保留为“特殊”SQL 字符的字符。

我正在处理的具体问题是我无法控制插入到我的数据库中的可能的“文本”,因为它们的文本是由我的应用程序生成的。

我的应用程序无法正确插入的一个示例是,当出现包含单引号的错误消息时。 SQL 语句当然使用单引号插入文本,因此我不能插入也包含单引号的文本(在使用 ascii 值 char(##) 函数之外)。我正在处理的问题是,我将应用程序的输出设置为一个字符串变量,然后插入到我的数据库中,这样我就可以记录活动,无论是标准输出还是捕获错误。

如何在避免所有 SQL 特殊字符的同时简单地插入字符串变量中包含的内容?

我是否需要在插入之前手动考虑所有 SQL 特殊字符并在我的字符串中替换它们?这听起来像是一个成功或失败,我希望已经建立了一些东西来适应这种情况。

用于理解要点的示例伪代码:

假设应用内发生错误,需要记录。错误字符串可能是:

错误字符串:“函数 calculateStats() 参数 'pBoolStatCheck' 中的错误为 Null”

现在我在我的应用程序中分配我的字符串变量并构建 SQL 插入字符串。

var insertString = "Error in function calculateStats() parameter 'pBoolStatCheck' is Null"


INSERT INTO outputLog(outputLogText) 
VALUES ('insertString');   --This will Fail

--Fails due to the variable 'insertString' containing single quotes.
INSERT INTO outputLog(outputLogText) 
VALUES ('Error in function calculateStats() parameter 'pBoolStatCheck' is Null');

在结束时 - 由于我无法控制我的应用程序可以创建的文本,我如何考虑所有可能破坏我的插入的字符?

我当前遇到此问题的应用程序的代码是用 Visual Basic 编写的。我正在使用的数据库是 SQLite。

根据这篇帖子收到的答案的最终解决方案:

Public Sub saveOutputLog(pTextOutput, pTextColor, pNumNewLines, plogType, pMethodSub)

    Dim strTableName As String = "outputLog"
    Dim sqlInsert As String = "INSERT INTO " & strTableName & "(" &
                              "outputLog, logColor, numNewLines, logType, method" &
                              ") VALUES (@outputLog, @logColor, @numNewLines, @logType, @method);"

    Try
        'Open the Database
        outputLogDBConn.Open()

        'Create/Use a command object via the connection object to insert data into the outputLog table
        Using cmd = outputLogDBConn.CreateCommand() 
            cmd.CommandType = CommandType.Text
            cmd.CommandText = sqlInsert
            cmd.Parameters.AddWithValue("@outputLog", pTextOutput)
            cmd.Parameters.AddWithValue("@logColor", pTextColor)
            cmd.Parameters.AddWithValue("@numNewLines", pNumNewLines)
            cmd.Parameters.AddWithValue("@logType", plogType)
            cmd.Parameters.AddWithValue("@method", pMethodSub)

            'Execute the command using above Insert and added Parameters.
            cmd.ExecuteNonQuery()

        End Using 'Using outputLogDBComm

        outputLogDBConn.Close()

    Catch ex As Exception

        outputLogDBConn.Close()

    End Try

End Sub

【问题讨论】:

  • 您将使用参数化查询在运行时绑定字符串。这也将防止您出现 SQL 注入漏洞。如果我知道您使用的语言会有所帮助,这样我就可以为您指明正确的方向。
  • @user2827048 我当前的应用程序遇到此问题的代码是用 Visual Basic 编写的。我正在使用的数据库是 SQLite。我还更新了原帖。

标签: sql vb.net sqlite


【解决方案1】:

这个问题与防止代码中的 SQL 注入漏洞的问题非常相似。查询很容易被破坏,虽然您的查询以一种无害且烦人的方式破坏,但这些查询可以达到某些输入可以完全破坏您的数据库的程度!

解决此问题的最佳方法之一是使用参数化查询。这种方法非常简单;您首先使用“占位符”为要发送的参数编写查询。准备好程序后,您可以将这些参数“绑定”到占位符。

它看起来像下面这样:

Dim command = New SqlCommand("INSERT INTO outputLog(outputLogText) VALUES  (@stringToInsert)", connection);
.
.
.
code
.
.
.
command.Parameters.AddWithValue("@stringToInsert", errorMessage)
.
.
.
execute query

在上面您看到@stringToInsert 是占位符,仅在以后绑定。变量 errorMessage 包含什么并不重要,因为它不会导致查询以输入可能导致其中断的方式运行。

这方面有很多资源:

https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.prepare?view=netframework-4.7.2

【讨论】:

    【解决方案2】:

    像连接这样的数据库对象不仅需要关闭,还需要释放。 Using 块将确保即使出现错误也会发生这种情况。

    出于多种原因,.Add 优于 .AddWithValue。见https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/和http://www.dbdelta.com/addwithvalue-is-evil/
    .Add 的参数是参数的名称、数据库中的数据类型以及可选的字段大小。您将需要检查最后 2 个数据库。

    在执行前的最后一分钟打开连接。

    如果您将 OleDb 与 Access 一起使用,则需要确保参数的添加顺序与它们在 sql 语句中出现的顺序相同。

        Using cn As New SqlConnection("Your connection string")
            Using cmd As New SqlCommand("INSERT INTO outputLog(outputLogText) VALUES (@outputLogText);", cn)
                cmd.Parameters.Add("@outputLogText", SqlDbType.VarChar, 100).Value = TextBox1.Text
                cn.Open()
                cmd.ExecuteNonQuery()
            End Using
        End Using
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 2016-06-10
      • 1970-01-01
      • 2019-05-25
      • 1970-01-01
      相关资源
      最近更新 更多