我想阅读用户输入并将其插入mysql语句,从而执行它。
public class DropTable {
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/test";
Connection connection = null;
String input;
public void deleteColumns(){
try {
connection = DriverManager.getConnection(DATABASE_URL,"jezza", "10");
Statement stmt = connection.createStatement();
Scanner value = new Scanner(System.in);
System.out.println("Enter the value to delete");
input = value.nextLine();
stmt.executeUpdate("delete from books where LastName = "+value.toString() );
}// end try
catch (SQLException ex) {
System.out.println("Error "+ex.toString());
System.out.println("dropTable");
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} // end catch
} //end deleteColumns
}
扫描程序无法接受用户输入并将其插入查询中。以下是我得到的错误。根据错误产生查询的语句。我该怎么办?
> Error com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false' at line 1
dropTable
SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[delimiters=\p{javaWhitespace}+][position=0][match valid=false][need input=false' at line 1
SQLState: 42000
VendorError: 1064
最佳答案
这个
input = value.nextLine();
stmt.executeUpdate("delete from books where LastName = "+value.toString() );
应该
input = value.nextLine();
stmt.executeUpdate("delete from books where LastName = " + input );
但是也不要这样。您正在为SQL注入做好准备。使用
PreparedStatement
。 Here's a tutorial.关于java - 用户输入并附加到mysql中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20732738/