小编典典

在SQL参数化查询中转义单引号'

sql

我正在尝试在vb.net中使用sql查询插入数据,如下所示。名称= corp int’l poc = 1

当我尝试插入时,出现错误(“字符串’“之后的未封闭的引号)。当我尝试仅用1个单引号插入名称时,就会发生这种情况。

因此,我添加了一个replace函数,以将2个单引号替换为1个单引号来转义符号。没有错误,但是当我查看数据库时,添加了2个单引号而不是1个。

谁能告诉我如何通过参数化查询来避免使用单引号?谢谢!

 Public Function InsertData(ds As DataSet) As Boolean
    Dim cmd As New SqlCommand
    Dim cmd1 As New SqlCommand
    Dim status As Boolean
    Dim name As String
    Dim poc As String

    Dim id_p As New SqlParameter("id", SqlDbType.VarChar)
    Dim name_p As New SqlParameter("name", SqlDbType.VarChar)

    cmd.Parameters.Add(id_p)
    cmd.Parameters.Add(name_p)

    For i = 0 To ds.Tables(0).Rows.Count - 1

        If checkExists(ds.Tables(0).Rows(i)(1).ToString(), ds.Tables(0).Rows(i)(2).ToString(), ds.Tables(0).Rows(i)(3).ToString()) = True Then


            name = ds.Tables(0).Rows(i)(1).ToString()
            poc = ds.Tables(0).Rows(i)(2).ToString()

            If name.Contains("'") Then
                name = name.Replace("'", "''")
            End If
            If poc.Contains("'") Then
                poc = poc.Replace("'", "'")
            End If

            name_p.SqlValue = name
            id_p.SqlValue = poc


            cmd.CommandText = "INSERT INTO Code (Name,ID)" _
                              & " VALUES (@name,@id)"

            status = ExecuteNonQuerybySQLCommand(cmd)
        End If
    Next

    Return status

End Function


Dim strcon As String = "Data Source=x.x.x.x,1433;Network Library=DBMSSOCN;Initial Catalog=code_DB;User ID=xxx;Password=xxx;"

 Public Function ExecuteNonQuerybySQLCommand(ByVal cmd As SqlCommand) As Boolean
    Dim sqlcon As New SqlConnection
    Dim i As Integer = 0

    sqlcon.ConnectionString = strcon
    cmd.Connection = sqlcon

    Try
        sqlcon.Open()
        i = cmd.ExecuteNonQuery()
        sqlcon.Close()

        If i > 0 Then
            Return True
        Else
            Return False
        End If

    Catch ex As Exception
        Console.Write(ex)
        Return False
    End Try
End Function

阅读 299

收藏
2021-04-07

共1个答案

小编典典

作为参数传递的值(即SqlParameter对象)不需要转义。这是因为客户端API使用RPC调用来执行查询,而查询本身和参数是分别传递的。通过RPC调用,实际参数值将通过TDS协议以本机(二进制)格式发送到SQL
Server,而不是嵌入到语句中。这样可以减轻SQL注入的顾虑,并提供其他好处,例如强类型化和改进的性能。

2021-04-07