今天跟着书里面的例子,练习了下数据库连接。
出现了该报错:
java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
这是问题的关键。
原因是在执行INSERT插入语句时,PreparedStatement使用的是executeQuery()
。
查文档可知:
execute()
执行此 PreparedStatement对象中的SQL语句,这可能是任何类型的SQL语句。
executeQuery()
执行此 PreparedStatement对象中的SQL查询,并返回查询 PreparedStatement的 ResultSet对象。
executeUpdate()
执行在该SQL语句PreparedStatement对象,它必须是一个SQL数据操纵语言(DML)语句,如INSERT , UPDATE或DELETE ; 或不返回任何内容的SQL语句,例如DDL语句。
因此把代码里的executeQuery()
改为executeUpdate()
,问题解决。
出错原因是书籍里的代码都是错的!!!