一般开发中使用preparedStatement,不使用Statement。preparedStatement是Statement的子接口,继承了Statement的所有功能。preparedStatement有两大特点:
1.当使用Statement多次执行同一条Sql语句时,将会影响执行效率。使用PreparedStatement的对象可以对Sql语句进行预编译。执行速度高于Statement .
2.PreparedStatement 可以执行动态的Sql语句。动态的Sql语句就是在SQL语句中提供参数。可以大大提高程序的灵活性和执行效率。
动态SQL语句:insert into student value(?,?,?,?)
3.在执行SQL语句之前必须对?进行赋值。 PreparedStatement接口有大量的SetXXX()方法。
pst.setString(1, student.getSno());PreparedStatement为第一个?,设置值。值得获取是Student类的get()方法。
所以要写一个Student类。里面有get、set、以及构造方法。
4.对数据库的链接操作和关闭操作放到一个类里面封装起来。
package revjdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import model.student;
import Util.Dbutil;
public class PreparementDemo {
public static Dbutil db=new Dbutil();
public static int addStudent(student student) throws Exception
{
Connection con=db.getCon();
String sql="insert into student values(?,?,?,?)";
PreparedStatement pst=con.prepareStatement(sql);
pst.setString(1, student.getSno());
pst.setString(2, student.getName());
pst.setInt(3, student.getAge());
pst.setString(4, student.getSex());
int rst=pst.executeUpdate();//preparedStatement 可以执行SQL语句。返回的结果是执行了多少行。
db.close(con, pst);
System.out.println("共改动了"+rst+"行");
return rst;
}
public static void main(String[] args) throws Exception{
student student=new student("9804","跳跳",29,"1");//插入操作执行完一遍之后,不能继续执行,因为主键会重复
student student2=new student("9801","俏俏",29,"1");
addStudent(student);
addStudent(student2);
}
}
package model;
public class student {
private String sno;
private String name;
private int age;
private String sex;
public student(String sno, String name, int age, String sex) {
super();
this.sno = sno;
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSno() {
return sno;
}
public void setSno(String sno) {
this.sno = sno;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
package Util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Dbutil {
// 驱动名称
private static String jdbcName = "com.mysql.jdbc.Driver";
// 数据库地址
private static String dbUrl = "jdbc:mysql://localhost:3306/student";
// 用户名
private static String dbUserName = "root";
// 密码
private static String dbPassword = "123456";
public Connection getCon() throws Exception {
Class.forName(jdbcName);
Connection con;
con = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
return con;
}
public void close(Connection con, Statement st)throws Exception {
if (st != null)
st.close();
if (con != null) {
con.close();
}
}
}