PreparedStatement介面
阿新 • • 發佈:2018-12-09
一般開發中使用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();
}
}
}