一、JDBC
1.概念:Java DataBase Connectivity Java 數據庫連接, Java語言操作數據庫
* JDBC本質:其實是官方(sun公司)定義的一套操作所有關系型數據庫的規則,即接口。各個數據庫廠商去實現這套接口,提供數據庫驅動jar包。我們可以使用這套接口(JDBC)編程,真正執行的代碼是驅動jar包中的實現類。
2.快速入門
//1. 導入驅動jar包 //2.注冊驅動 Class.forName("com.mysql.jdbc.Driver"); //3.獲取數據庫連接對象 Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db3", "root", "root"); //4.定義sql語句 String sql = "update account set balance = ? where id = ?"; //5.獲取執行sql的對象 Statement PreparedStatement pst =con.prepareStatement(sql); pst.setDouble(1, 500); pst.setDouble(2, 1000); //6.執行sql int count = stmt.executeUpdate(sql); //7.處理結果 System.out.println(count); //8.釋放資源 stmt.close(); conn.close();
3.詳解各個對象:
3.1. DriverManager:驅動管理對象
功能:
1.注冊驅動:告訴程序該使用哪一個數據庫驅動jar
2.獲取數據庫連接;
3.2. Connection:數據庫連接對象
功能:1. 獲取執行sql 的對象
* Statement createStatement()
* PreparedStatement prepareStatement(String sql)
2.管理事務
* 開啟事務:setAutoCommit(boolean autoCommit) :調用該方法設置參數為false,即開啟事務
* 在執行sql之前開啟事務
* 提交事務:commit()
* 當所有sql都執行完提交事務
* 回滾事務:rollback()
* 在catch中回滾事務
二、數據庫連接池
1.概念:是一個容器(集合),存放數據庫連接的容器。當系統初始化好后,容器被創建,容器中會申請一些連接對象,當用戶來訪問數據庫時,從容器中獲取連接對象,用戶訪問完之后,會將連接對象歸還給容器。
2. 好處: 節約資源、用戶訪問高效
3.實現: 標准接口:DataSource javax.sql包下的;
方法: 獲取連接:getConnection();
4.連接池技術
4.1.c3p0: 數據庫連接技術
步驟:
1. 導入jar包 (兩個) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar ,
* 不要忘記導入數據庫驅動jar包
2. 定義配置文件:
* 名稱: c3p0.properties 或者 c3p0-config.xml
* 路徑:直接將文件放在src目錄下即可。
3. 創建核心對象 數據庫連接池對象 ComboPooledDataSource
4. 獲取連接: getConnection
public class C3_P0utils { private static ComboPooledDataSource dataSource = new ComboPooledDataSource("oracle"); public static DataSource getDataSource() { return dataSource; } public static Connection getConnection() { try { return dataSource.getConnection(); } catch (SQLException e) { throw new RuntimeException(); } } }
<!--c3p0-config配置文件-->
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql:///mbase</property> <property name="user">root</property> <property name="password">123</property> <property name="initialPoolSize">5</property> <property name="maxPoolSize">20</property> </default-config> </c3p0-config>
4.2.Druid:數據庫連接技術,阿里巴巴提供
步驟:
1. 導入jar包 druid-1.0.9.jar
2. 定義配置文件:
* 是properties形式的
* 可以叫任意名稱,可以放在任意目錄下
3. 加載配置文件。Properties
4. 獲取數據庫連接池對象:通過工廠來來獲取 DruidDataSourceFactory
5. 獲取連接:getConnection
public class JDBCUtils { //1.定義成員變量 DataSource private static DataSource ds ; static{ try { //1.加載配置文件 Properties pro = new Properties(); pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")); //2.獲取DataSource ds = DruidDataSourceFactory.createDataSource(pro); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * 獲取連接 */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } /** * 釋放資源 */ public static void close(Statement stmt,Connection conn){ /* if(stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close();//歸還連接 } catch (SQLException e) { e.printStackTrace(); } }*/ close(null,stmt,conn); } public static void close(ResultSet rs , Statement stmt, Connection conn){ if(rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(stmt != null){ try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close();//歸還連接 } catch (SQLException e) { e.printStackTrace(); } } } /** * 獲取連接池方法 */ public static DataSource getDataSource(){ return ds; } }
//druid.properties文件
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mbase
username=root
password=123
三、DButils
例:
//1.創建按核心類QueryRunner QueryRunner qr = new QueryRunner(C3_P0utils.getDataSource()); //增加 String sql="insert into sort values(null,?,?,?)"; //3.為占位符設置值 Object[] params = {"超萌二哈",190,"拆家拆家"}; //4.執行添加操作 int row=qr.update(sql, params); //修改 String sql="update sort set sname=? where id=?"; Object[] param= {"二哈",19}; int row =qr.update(sql,param); //刪除 String sql ="delete from sort where id=?"; int row = qr.update(sql,20); //查詢 //1.將結果集的每一行數據封裝成JavaBean對象 : BeanListHandler List<Users> users=qr.query(sql, new BeanListHandler<Users>(Users.class)); //2.將結果集的一行數據封裝成JavaBean對象:BeanHandler Users users=qr.query(sql,new BeanHandler<Users>(Users.class), param); //3.查詢所有個數:ScalarHandler Long count=(Long) qr.query(sql, new ScalarHandler<Object>()); //4.MapListHandler List<Map<String,Object>> list=qr.query(sql, new MapListHandler()); //5.將某列的值封裝到List集合中 String sql="select * from product where pname like ? limit 0,8"; List<Object> query = qr.query(sql, new ColumnListHandler("pname"), "%"+word+"%");
四、JdbcTemplate
1.Spring框架對JDBC的簡單封裝。提供了一個JDBCTemplate對象簡化JDBC的開發
* 步驟:
1. 導入jar包
2. 創建JdbcTemplate對象。依賴於數據源DataSource
* JdbcTemplate template = new JdbcTemplate(ds);
3. 調用JdbcTemplate的方法來完成CRUD的操作
* update():執行DML語句。增、刪、改語句
* queryForMap():查詢結果將結果集封裝為map集合,將列名作為key,將值作為value 將這條記錄封裝為一個map集合
* 注意:這個方法查詢的結果集長度只能是1
* queryForList():查詢結果將結果集封裝為list集合
* 注意:將每一條記錄封裝為一個Map集合,再將Map集合裝載到List集合中
* query():查詢結果,將結果封裝為JavaBean對象
* query的參數:RowMapper
* 一般我們使用BeanPropertyRowMapper實現類。可以完成數據到JavaBean的自動封裝
* new BeanPropertyRowMapper<類型>(類型.class)
* queryForObject:查詢結果,將結果封裝為對象
* 一般用於聚合函數的查詢
例:
//1. 獲取JDBCTemplate對象 private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); //添加一條記錄 int count = template.update(sql, 1015, "郭靖", 10); //刪除剛才添加的記錄 int count = template.update(sql, 1015); //查詢id為1001的記錄,將其封裝為Map集合 Map<String, Object> map = template.queryForMap(sql, 1001,1002); // 查詢所有記錄,將其封裝為List List<Map<String, Object>> list = template.queryForList(select * from emp); //查詢總記錄數 Long total = template.queryForObject(sql, Long.class); //查詢所有記錄,將其封裝為Emp對象的List集合 List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));