【问题标题】:How to set variables into a JDBC statement?如何将变量设置为 JDBC 语句?
【发布时间】:2023-03-15 04:59:01
【问题描述】:

例如,当我尝试插入变量时它可以工作:

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

但无法使用变量插入

String a=username.getText();
String b=password.getText();

try {
    Class.forName("com.mysql.jdbc.Driver");  
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/java_db1","root","");  

    Statement stmt=con.createStatement();        
    String insertStr="INSERT INTO  table1(username1,password1) VALUES(a,b);";
    stmt.executeUpdate(insertStr);
} catch (Exception e) { }

【问题讨论】:

  • String insertStr="INSERT INTO table1(username1,password1) VALUES("+strA+","+strB+");";

标签: java mysql jdbc


【解决方案1】:

使用 [PreparedStatement][1] 代替您的方式,因为您的方式可能成为 SQL 注入或语法错误的受害者:

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

出于安全考虑,我不建议使用getText()获取密码,而是使用getPassword(),这样您就可以使用:

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

看看这个:

【讨论】:

  • 第 2 行有一个小的语法错误,冒号不应该在尝试资源时出现。谢谢你的回答:)
  • 感谢@joshpetit 的评论,你的意思是我不明白你的意思。
  • 这里有一个 * 分号:try (PreparedStatement pst = con.prepareStatement(insertStr);) 在 insertStr 之后。
  • 这可能是一个单独的帖子,但是有没有办法为多个字段使用相同的变量?即在准备好的语句中对两个问号使用相同的变量?
  • @joshpetit 是的,它是不必要的分号,您可以编辑我的问题以让您的跟踪:) 关于您的问题,是的,您可以使用pst.setString(1, sameThing); pst.setString(2, sameThing);
【解决方案2】:

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

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

应该这样做,但我建议在这里使用准备好的语句:https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html

【讨论】:

  • 你不应该直接在 SQL 字符串中使用变量,因为这很容易受到数据库注入攻击。
  • @TravisStevens 这就是为什么我推荐准备好的陈述......
【解决方案3】:

在sql中插入变量值最常用的方法是使用PreparedStatement Object

使用此对象,您可以将变量值添加到 SQL 查询中,而不必担心 SQL 注入。 这是 PreparedStatement 的示例:

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

这比使用这样的字符串连接更安全:VALUES("+a+","+b+");

查看 Java 文档了解更多信息;)

【讨论】:

    猜你喜欢
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    相关资源
    最近更新 更多