【发布时间】: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。我还更新了原帖。