当我尝试插入变量时,它会起作用,例如:
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) { }
3条答案
按热度按时间fkaflof61#
将变量值插入sql的最常用方法是使用preparedstatement对象
使用此对象,您可以将变量值添加到sql查询中,而不用担心sql注入。以下是preparedstatement的示例:
这比像这样使用字符串串联更安全:
VALUES("+a+","+b+");
有关更多信息,请参阅javadoc;)xa9qqrwz2#
使用
PreparedStatement
而不是您的方式,因为您的方式可能是sql注入或语法错误的受害者:出于安全考虑,我不建议使用
getText()
,而不是使用getPassword()
,因此您可以使用:看看这个:
gettext()与getpassword()
为什么不推荐使用jpasswordfield中的gettext()?
kb5ga3dv3#
因为您将“a”和“b”作为字符串插入,而不是它们的变量值。
应该这样做,但我建议在这里使用一个事先准备好的声明:https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html