深入分析JavaWeb Item28 -- 使用JDBC對資料庫進行CRUD
一、statement對象介紹
Jdbc中的statement對象用於向資料庫發送SQL語句,想完成對資料庫的增刪改查,只需要通過這個對象向資料庫發送增刪改查語句即可。
Statement對象的executeUpdate方法,用於向資料庫發送增、刪、改的sql語句,executeUpdate執行完後,將會返回一個整數(即增刪改語句導致了資料庫幾行資料發生了變化)。
Statement.executeQuery方法用於向資料庫發送查詢語句,executeQuery方法返回代表查詢結果的ResultSet對象。
1.1、CRUD操作-create
使用executeUpdate(String sql)方法完成資料添加操作,樣本操作:
Statement st = conn.createStatement(); String sql = "insert into user(….) values(…..) "; int num = st.executeUpdate(sql); if(num>0){ System.out.println("插入成功!!!");}
1.2、CRUD操作-update
使用executeUpdate(String sql)方法完成資料修改操作,樣本操作:
Statement st = conn.createStatement(); String sql = “update user set name=‘’ where name=‘’"; int num = st.executeUpdate(sql); if(num>0){ System.out.println(“修改成功!!!"); }
1.3、CRUD操作-delete
使用executeUpdate(String sql)方法完成資料刪除操作,樣本操作:
Statement st = conn.createStatement(); String sql = “delete from user where id=1; int num = st.executeUpdate(sql); if(num>0){ System.out.println(“刪除成功!!!"); }
1.4、CRUD操作-select
使用executeQuery(String sql)方法完成資料查詢操作,樣本操作:
Statement st = conn.createStatement(); String sql = “select * from user where id=1; ResultSet rs = st.executeUpdate(sql); while(rs.next()){ //根據擷取列的資料類型,分別調用rs的相應方法映射到java對象中 }
二、使用jdbc對資料庫增刪改查
2.1、搭建實驗環境
1、在mysql中建立一個庫,並建立user表和插入表的資料。
SQL指令碼如下:
create database jdbcStudy;use jdbcStudy;create table users( id int primary key, name varchar(40), password varchar(40), email varchar(60), birthday date);
2、建立一個JavaWeb工程,並匯入MySQL資料庫驅動。
3、在src目錄下建立一個db.properties檔案,如所示:
在db.properties中編寫MySQL資料庫的串連資訊,代碼如下所示:
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/jdbcStudy username=root password=XDP
4、編寫一個JdbcUtils工具類,用於串連資料庫,擷取資料庫連接和釋放資料庫連接,代碼如下:
package me.gacl.utils;import java.io.InputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;public class JdbcUtils { private static String driver = null; private static String url = null; private static String username = null; private static String password = null; static{ try{ //讀取db.properties檔案中的資料庫連接資訊 InputStream in = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties"); Properties prop = new Properties(); prop.load(in); //擷取資料庫連接驅動 driver = prop.getProperty("driver"); //擷取資料庫連接URL地址 url = prop.getProperty("url"); //擷取資料庫連接使用者名稱 username = prop.getProperty("username"); //擷取資料庫連接密碼 password = prop.getProperty("password"); //載入資料庫驅動 Class.forName(driver); }catch (Exception e) { throw new ExceptionInInitializerError(e); } } /** * @Method: getConnection * @Description: 擷取資料庫連接對象 * @Anthor:孤傲蒼狼 * * @return Connection資料庫連接對象 * @throws SQLException */ public static Connection getConnection() throws SQLException{ return DriverManager.getConnection(url, username,password); } /** * @Method: release * @Description: 釋放資源, * 要釋放的資源套件括Connection資料庫連接對象,負責執行SQL命令的Statement對象,儲存查詢結果的ResultSet對象 * @Anthor:孤傲蒼狼 * * @param conn * @param st * @param rs */ public static void release(Connection conn,Statement st,ResultSet rs){ if(rs!=null){ try{ //關閉儲存查詢結果的ResultSet對象 rs.close(); }catch (Exception e) { e.printStackTrace(); } rs = null; } if(st!=null){ try{ //關閉負責執行SQL命令的Statement對象 st.close(); }catch (Exception e) { e.printStackTrace(); } } if(conn!=null){ try{ //關閉Connection資料庫連接對象 conn.close(); }catch (Exception e) { e.printStackTrace(); } } }}
2.2、使用statement對象完成對資料庫的CRUD操作
測試代碼如下:
package me.gacl.demo;import java.sql.Connection;import java.sql.ResultSet;import java.sql.Statement;import me.gacl.utils.JdbcUtils;import org.junit.Test;/*** @ClassName: JdbcCRUDByStatement* @Description: 通過Statement對象完成對資料庫的CRUD操作* @author: 孤傲蒼狼* @date: 2014-9-15 下午11:22:12**/ public class JdbcCRUDByStatement { @Test public void insert(){ Connection conn = null; Statement st = null; ResultSet rs = null; try{ //擷取一個資料庫連接 conn = JdbcUtils.getConnection(); //通過conn對象擷取負責執行SQL命令的Statement對象 st = conn.createStatement(); //要執行的SQL命令 String sql = "insert into users(id,name,password,email,birthday) values(3,'白虎神皇','123','[email protected]','1980-09-09')"; //執行插入操作,executeUpdate方法返回成功的條數 int num = st.executeUpdate(sql); if(num>0){ System.out.println("插入成功!!"); } }catch (Exception e) { e.printStackTrace(); }finally{ //SQL執行完成之後釋放相關資源 JdbcUtils.release(conn, st, rs); } } @Test public void delete(){ Connection conn = null; Statement st = null; ResultSet rs = null; try{ conn = JdbcUtils.getConnection(); String sql = "delete from users where id=3"; st = conn.createStatement(); int num = st.executeUpdate(sql); if(num>0){ System.out.println("刪除成功!!"); } }catch (Exception e) { e.printStackTrace(); }finally{ JdbcUtils.release(conn, st, rs); } } @Test public void update(){ Connection conn = null; Statement st = null; ResultSet rs = null; try{ conn = JdbcUtils.getConnection(); String sql = "update users set name='孤傲蒼狼',email='[email protected]' where id=3"; st = conn.createStatement(); int num = st.executeUpdate(sql); if(num>0){ System.out.println("更新成功!!"); } }catch (Exception e) { e.printStackTrace(); }finally{ JdbcUtils.release(conn, st, rs); } } @Test public void find(){ Connection conn = null; Statement st = null; ResultSet rs = null; try{ conn = JdbcUtils.getConnection(); String sql = "select * from users where id=3"; st = conn.createStatement(); rs = st.executeQuery(sql); if(rs.next()){ System.out.println(rs.getString("name")); } }catch (Exception e) { e.printStackTrace(); }finally{ JdbcUtils.release(conn, st, rs); } }}
三、PreparedStatement對象介紹
PreperedStatement是Statement的子類,它的執行個體對象可以通過調用Connection.preparedStatement()方法獲得,相對於Statement對象而言:PreperedStatement可以避免SQL注入的問題。
Statement會使資料庫頻繁編譯SQL,可能造成資料庫緩衝區溢位。PreparedStatement可對SQL進行先行編譯,從而提高資料庫的執行效率。並且PreperedStatement對於sql中的參數,允許使用預留位置的形式進行替換,簡化sql語句的編寫。
3.1、使用PreparedStatement對象完成對資料庫的CRUD操作
測試代碼如下:
package me.gacl.demo;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.Date;import me.gacl.utils.JdbcUtils;import org.junit.Test;/*** @ClassName: JdbcCRUDByPreparedStatement* @Description: 通過PreparedStatement對象完成對資料庫的CRUD操作* @author: 孤傲蒼狼* @date: 2014-9-15 下午11:21:42**/ public class JdbcCRUDByPreparedStatement { @Test public void insert(){ Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try{ //擷取一個資料庫連接 conn = JdbcUtils.getConnection(); //要執行的SQL命令,SQL中的參數使用?作為預留位置 String sql = "insert into users(id,name,password,email,birthday) values(?,?,?,?,?)"; //通過conn對象擷取負責執行SQL命令的prepareStatement對象 st = conn.prepareStatement(sql); //為SQL語句中的參數賦值,注意,索引是從1開始的 /** * SQL語句中各個欄位的類型如下: * +----------+-------------+ | Field | Type | +----------+-------------+ | id | int(11) | | name | varchar(40) | | password | varchar(40) | | email | varchar(60) | | birthday | date | +----------+-------------+ */ st.setInt(1, 1);//id是int類型的 st.setString(2, "白虎神皇");//name是varchar(字串類型) st.setString(3, "123");//password是varchar(字串類型) st.setString(4, "[email protected]");//email是varchar(字串類型) st.setDate(5, new java.sql.Date(new Date().getTime()));//birthday是date類型 //執行插入操作,executeUpdate方法返回成功的條數 int num = st.executeUpdate(); if(num>0){ System.out.println("插入成功!!"); } }catch (Exception e) { e.printStackTrace(); }finally{ //SQL執行完成之後釋放相關資源 JdbcUtils.release(conn, st, rs); } } @Test public void delete(){ Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try{ conn = JdbcUtils.getConnection(); String sql = "delete from users where id=?"; st = conn.prepareStatement(sql); st.setInt(1, 1); int num = st.executeUpdate(); if(num>0){ System.out.println("刪除成功!!"); } }catch (Exception e) { e.printStackTrace(); }finally{ JdbcUtils.release(conn, st, rs); } } @Test public void update(){ Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try{ conn = JdbcUtils.getConnection(); String sql = "update users set name=?,email=? where id=?"; st = conn.prepareStatement(sql); st.setString(1, "gacl"); st.setString(2, "[email protected]"); st.setInt(3, 2); int num = st.executeUpdate(); if(num>0){ System.out.println("更新成功!!"); } }catch (Exception e) { e.printStackTrace(); }finally{ JdbcUtils.release(conn, st, rs); } } @Test public void find(){ Connection conn = null; PreparedStatement st = null; ResultSet rs = null; try{ conn = JdbcUtils.getConnection(); String sql = "select * from users where id=?"; st = conn.prepareStatement(sql); st.setInt(1, 1); rs = st.executeQuery(); if(rs.next()){ System.out.println(rs.getString("name")); } }catch (Exception e) { }finally{ JdbcUtils.release(conn, st, rs); } }}
以上就是使用JDBC對資料庫進行CRUD的簡單總結。