4、使用PreparedStatement接口实现增,删,改操作(常用)
生活随笔
收集整理的這篇文章主要介紹了
4、使用PreparedStatement接口实现增,删,改操作(常用)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第一節:PreparedStatement接口引入
PreparedStatement 是 Statement 的子接口,屬于預處理操作,與直接使用 Statement 不同的是,PreparedStatement
在操作時,是先在數據表中準備好了一條 SQL 語句,但是此 SQL 語句的具體內容暫時不設置,而是之后再進行設置。
(以后開發一般用 PreparedStatement,不用 Statement)
第二節:使用PreparedStatement接口實現添加數據操作
實例1:
1、學生模型類
2、工具類
public class DbUtil {private static String dbUrl="jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=UTF-8";private static String dbUserName="root";private static String dbPassword="root";private static String jdbcName="com.mysql.jdbc.Driver";/*** 獲取數據庫連接* @return* @throws Exception*/public Connection getCon() throws Exception{Class.forName(jdbcName);Connection con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword); return con;}/*** 關閉連接* @param con* @throws Exception*/public void close(Statement stmt,Connection con)throws Exception{if(stmt!=null){stmt.close();if(con!=null){con.close();}}} }3、測試類
public class jdbcTest {private static DbUtil dbUtil=new DbUtil();private static Student student=new Student();/*** 添加數據* @param stuName* @param stuSex* @param stuAge* @return*/public static int addStudent(Student student)throws Exception{Connection con=dbUtil.getCon();//獲取連接String sql="insert into student values(null,?,?,?)";PreparedStatement pstmt=con.prepareStatement(sql);pstmt.setString(1, student.getStuName());//給第一個?設置值pstmt.setString(2, student.getStuSex());//給第二個?設置值pstmt.setInt(3, student.getStuAge());給第三個?設置值int result=pstmt.executeUpdate();dbUtil.close(pstmt, con);//pstmt是子類,可以關閉return result;}public static void main(String[] args) throws Exception {Student student=new Student("大黃蜂","女",8979);addStudent(student);} }第三節:使用PreparedStatement接口實現更新數據操作
實例:
3、測試類
第四節:使用PreparedStatement接口實現刪除數據操作
實例:
3、測試類
運行結果:
總結
以上是生活随笔為你收集整理的4、使用PreparedStatement接口实现增,删,改操作(常用)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2、JDBC连接数据库
- 下一篇: 6、处理大数据对象(CLOB 数据小说+