老师好!
我用的是Mysql数据库,预处理添加数据的部分是不是有些语句是需要修改的?
我按照书上的代码运行,数据库能连接成功,也能查找数据,执行修改前的数据都能显示出来。
但从预处理添加数据部分就开始出现这种错误提示:
java.sql.SQLException: No value specified for parameter 4
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.PreparedStatement.checkAllParametersSet(PreparedStatement.java:2211)
at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2191)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2058)
at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)
at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)
at Renewal.main(Renewal.java:40)
原代码是:
import java.sql.*;
public class Renewal {
static Connection con;
static PreparedStatement sql;
static ResultSet res;
static Statement stmt ;
public Connection getConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test2?characterEncoding=utf8&useSSL=true", "root", "******");
System.out.println("数据库连接成功");
}catch(Exception e){
e.printStackTrace();
}
return con;
}
public static void main(String[] args) {
Renewal c = new Renewal();
con= c.getConnection();
try{
sql = con.prepareStatement("select * from tb_stu");
res = sql.executeQuery();
System.out.println("执行增加、修改、删除前的数据:");
while(res.next()){
String id = res.getString("id");
String name = res.getString("name");
String sex = res.getString("sex");
String birthday = res.getString("birthday");
System.out.print("编号:"+id);
System.out.print(" 姓名:"+name);
System.out.print(" 性别:"+sex);
System.out.print(" 生日:"+birthday);
System.out.println();
}
sql = con.prepareStatement("insert into tb_stu values(?,?,?,?)");
sql.setString(1, "彭丹");
sql.setString(2, "男");
sql.setString(3, "1990-12-12");
sql.executeUpdate();
sql = con.prepareStatement("update tb_stu set birthday=?where id = (select min(id) from tb_stu)");
sql.setString(1, "2012-12-02");
sql.executeUpdate();
stmt.executeUpdate("delete from tb_stu where id="+"(select min(id)from tb_stu)");
sql.setInt(1, 1);
sql.executeUpdate();
sql = con.prepareStatement("select*from tb_stu");
res = sql.executeQuery();
System.out.println("执行增加、修改、删除后的数据:");
while(res.next()){
String id = res.getString("id");
String name = res.getString("name");
String sex = res.getString("sex");
String birthday = res.getString("birthday");
System.out.print("编号:"+id);
System.out.print(" 姓名:"+name);
System.out.print(" 性别:"+sex);
System.out.print(" 生日:"+birthday);
System.out.println();
}
}catch(Exception e){
e.printStackTrace();
}
}
}