java—如何将变量设置到jdbc语句中?

dsf9zpds  于 2021-06-25  发布在  Mysql
关注(0)|答案(3)|浏览(374)

当我尝试插入变量时,它会起作用,例如:

  1. String insertStr="INSERT INTO table1(username1,password1) VALUES(\"john\",\"password\")";

但无法使用变量插入

  1. String a=username.getText();
  2. String b=password.getText();
  3. try {
  4. Class.forName("com.mysql.jdbc.Driver");
  5. Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/java_db1","root","");
  6. Statement stmt=con.createStatement();
  7. String insertStr="INSERT INTO table1(username1,password1) VALUES(a,b);";
  8. stmt.executeUpdate(insertStr);
  9. } catch (Exception e) { }
fkaflof6

fkaflof61#

将变量值插入sql的最常用方法是使用preparedstatement对象
使用此对象,您可以将变量值添加到sql查询中,而不用担心sql注入。以下是preparedstatement的示例:

  1. //[Connection initialized before]
  2. String insertStr="INSERT INTO table1(username1,password1) VALUES(?,?);";
  3. PreparedStatement myInsert = myConnectionVariable.prepareStatement(insertStr); // Your db will prepare this sql query
  4. myInsert.setString(1, a); //depending on type you want to insert , you have to specify the position of your argument inserted (starting at 1)
  5. myInsert.setString(2, b); // Here we set the 2nd '?' with your String b
  6. myInsert.executeUpdate(); // It will returns the number of affected row (Works for UPDATE,INSERT,DELETE,etc...)
  7. //You can use executeQuery() function of PreparedStatement for your SELECT queries

这比像这样使用字符串串联更安全: VALUES("+a+","+b+"); 有关更多信息,请参阅javadoc;)

xa9qqrwz

xa9qqrwz2#

使用 PreparedStatement 而不是您的方式,因为您的方式可能是sql注入或语法错误的受害者:

  1. String insertStr = "INSERT INTO table1(username1,password1) VALUES(?, ?)";
  2. try (PreparedStatement pst = con.prepareStatement(insertStr);) {
  3. pst.setString(1, a);
  4. pst.setString(2, b);
  5. pst.executeUpdate();
  6. }

出于安全考虑,我不建议使用 getText() ,而不是使用 getPassword() ,因此您可以使用:

  1. pst.setString(1, username.getText());
  2. pst.setString(2, new String(passwordField.getPassword()));

看看这个:
gettext()与getpassword()
为什么不推荐使用jpasswordfield中的gettext()?

展开查看全部
kb5ga3dv

kb5ga3dv3#

因为您将“a”和“b”作为字符串插入,而不是它们的变量值。

  1. String insertStr="INSERT INTO table1(username1,password1) VALUES("+a+","+b+");";

应该这样做,但我建议在这里使用一个事先准备好的声明:https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

相关问题