选择*from table where ="string with linebreaks"

Mar*_*iaH 1 java string select

我正在使用Java和MySQL,我必须从DB中选择这样的东西:

String sql = "SELECT type FROM test_case where input=" + inputTestCase;
Run Code Online (Sandbox Code Playgroud)

问题是inputTestCase字符串有时会有换行符.在这些情况下,我得到一个例外,例如:

You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server version
for the right syntax to use near '5
8
10' at line 2
Run Code Online (Sandbox Code Playgroud)

哪里:

'5
8
10'
Run Code Online (Sandbox Code Playgroud)

是我的inputTestCase.

我该怎么做才能让它Select发挥作用.谢谢大家的帮助!

PS:我没有初始化inputTestCase.该字符串的值来自DB.

Mar*_*ers 5

如果您使用JDBC,总是,总是使用PreparedStatement包括在查询动态数据的时候.如果不这样做,则极易受到SQL注入攻击,恶意用户可以在数据库上执行任意SQL命令.

作为对此的奖励,使用PreparedStatement将为您逃避输入,因此您不必担心在这种情况下对其进行消毒.

有关更多信息,请查看Java教程 - 使用准备语句.