java JDBC - 如何插入字符串值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10507857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:20:56  来源:igfitidea点击:

JDBC - How to insert a string value

javamysqlsqljdbc

提问by user1080390

When trying to insert the value of a string into my db using JDBC instead of inserting the String's value it inserts the String's name.

当尝试使用 JDBC 将字符串的值插入我的数据库而不是插入字符串的值时,它会插入字符串的名称。

I have a string named firstName, the value of this string is given by user input.

我有一个名为 firstName 的字符串,该字符串的值由用户输入给出。

Here is my sql statement:

这是我的sql语句:

String sql = "Insert INTO users (ID, firstName, address) VALUES ('124','+firstName()','123')";

回答by Paul Vargas

For various reasons, it is better to use java.sql.PreparedStatement. to execute statements with parameters. For example, if you want to avoid sql injectionattacks.

由于各种原因,最好使用java.sql.PreparedStatement. 执行带参数的语句。例如,如果您想避免sql 注入攻击。

See the examples in Using Prepared Statementsfrom The Java Tutorials.

请参阅使用Java 教程中的准备好的语句的示例

The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it.

使用带参数的 SQL 语句的优点是您可以使用相同的语句并在每次执行时为其提供不同的值。

PreparedStatement pstmt = conn.prepareStatement(
   "UPDATE EMPLOYEES SET FIRST_NAME= ? WHERE ID = ?");

pstmt.setString(1, "user1080390"); // set parameter 1 (FIRST_NAME)
pstmt.setInt(2, 101); // set parameter 2 (ID)

int rows = pstmt.executeUpdate(); // "rows" save the affected rows

回答by Karo

Try this

试试这个

String sql = "Insert INTO users (ID, firstName, address) VALUES ('124','"+firstName()+"','123')";

String sql = "Insert INTO users (ID, firstName, address) VALUES ('124','"+firstName()+"','123')";

To prevent sql injections, you need to escape the string before using in a query or try the prepared statements.

为了防止 sql 注入,您需要在查询中使用之前对字符串进行转义或尝试准备好的语句。

回答by asura

Something like this..

像这样的东西..

String firstName ="sample";
String sql = "Insert INTO users (ID, firstName, address) VALUES ('124',"+firstName+",'123')";