VB.Net:在查询字符串中使用带单引号的变量转义单引号

时间:2017-02-20 22:46:05

标签: sql sql-server vb.net

我的程序正在处理的一些记录是在日志表中创建一条记录:

instruments:'s'附近的语法不正确。字符串后的未闭合引号')))'。

代码使用内联查询将字符串变量的值连接到SELECT和SubQueries中的WHERE子句。

代码:

SQL = "SELECT instrument_id, description, sub_category_of, meta_instrument" _
& " FROM instruments " _
& " WHERE  (instrument_id IN " _
& " (SELECT instrument_id " _
    & "FROM instruments " _
    & "WHERE (description = '" & strn & "'))) " _
        & "OR (instrument_id IN " _
        & "    (SELECT sub_category_of " _
        & "     FROM instruments AS instruments_1 " _
        & "     WHERE (description = '" & strn & "'))) " _
        & "OR (instrument_id IN " _
        & "    (SELECT meta_instrument " _
        & "     FROM instruments AS instruments_1 " _
        & "     WHERE (description = '" & strn & "')))"

针对sql server执行的实际查询:

SELECT instrument_id, description, sub_category_of, meta_instrument _
FROM instrument_ref 
    WHERE  (instrument_id IN 
(SELECT instrument_id
    FROM instruments
    WHERE (description = 'Women's Choir'))) 
    OR (instrument_id IN 
        (SELECT sub_category_of
            FROM instruments AS instruments_1
            WHERE (description = 'Women's Choir')))
    OR (instrument_id IN
        (SELECT meta_instrument
            FROM instruments AS instruments_1
            WHERE (description = 'Women's Choir')))

我想请求如何处理单引号以便纠正此错误。我是否在'strn'变量中将其转义,或者我是否在内联查询中执行此操作?

非常感谢。

1 个答案:

答案 0 :(得分:2)

根据建议,使用参数:

SQL = "SELECT instrument_id, description, sub_category_of, meta_instrument" _
& " FROM instruments " _
& " WHERE  (instrument_id IN " _
& " (SELECT instrument_id " _
    & "FROM instruments " _
    & "WHERE (description = @description))) " _
        & "OR (instrument_id IN " _
        & "    (SELECT sub_category_of " _
        & "     FROM instruments AS instruments_1 " ... etc

然后,当您使用此SQL构造SqlCommand对象时,请使用命令对象的“.Parameters.AddWithValue()”方法添加名为“@description”的参数和相应的值。

顺便说一句,这可以通过输入“; drop table instruments”的描述来防止某人造成破坏。