如何转义SQL插入的单引号...当要插入的字符串在用户生成的变量中时 [英] How to escape single quotes for SQL insert...when string to insert is in a user generated variable

查看:103
本文介绍了如何转义SQL插入的单引号...当要插入的字符串在用户生成的变量中时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个使用jdbc执行的insert命令。部分是连接用户生成的字符串...这一切都有效,直到用户使用这样的字符串:

I am building an insert command to execute using jdbc. Part of it is to concatenate a user generated string...this all works until the user uses a string like this:

a'bcd

String userString="a'bcd";
String insertTableSQL = "INSERT INTO myTable "
                            + "(insertColumn) " 
                            + "VALUES("
                                +"'"+userString+"'"
                                +")";

statement.executeUpdate(insertTableSQL);


推荐答案

您可以执行以下任一操作:

You can do either of the below:


  1. 使用 PreparedStatement 类。 (推荐

String userString="a'bcd";
String myStatement = " INSERT INTO MYTABLE (INSERTCOLUMN) VALUES (?)";
PreparedStatement statement= con.prepareStatement   (myStatement );
statement.setString(1,userString);
statement.executeUpdate();


  • 逃避单引号。

  • Escape the single quotes.

    在SQL中,单引号将使用双引号进行转义。 ' - > ''

    In SQL, single quotes will be escaped by using double single quotes. ' --> ''

    String userString="a'bcd";
    String changedUserString = userString.replace("'","''");
            //changedUserString  = a''bcd
    String insertTableSQL = "INSERT INTO myTable (insertColumn) VALUES("
                            +" '"+changedUserString +"' )";
    


  • 这篇关于如何转义SQL插入的单引号...当要插入的字符串在用户生成的变量中时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆