简体   繁体   English

JDBC-如何插入字符串值

[英]JDBC - How to insert a string value

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将字符串的值插入到我的数据库中时,而不是插入String的值时,它将插入String的名称。

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')";

For various reasons, it is better to use java.sql.PreparedStatement . 由于各种原因,最好使用java.sql.PreparedStatement to execute statements with parameters. 执行带有参数的语句。 For example, if you want to avoid sql injection attacks. 例如,如果要避免sql注入攻击。

See the examples in Using Prepared Statements from 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

Try this 尝试这个

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注入,您需要先在查询中使用该字符串或对准备好的语句进行转义。

Something like this.. 像这样

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM