我想读取用户输入并将其插入到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
答案 0 :(得分:2)
这个
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.