JDBC:
1. 概念:Java DataBase Connectivity Java 數據庫連接, Java語言操作數據庫
JDBC本質:其實是官方(sun公司)定義的一套操作所有關係型數據庫的規則,即接口。各個數據庫廠商去實現這套接口,提供數據庫驅動jar包。我們可以使用這套接口(JDBC)編程,真正執行的代碼是驅動jar包中的實現類。
如下圖所示:
2. 快速入門:
- 步驟:
- 導入驅動jar包 mysql-connector-java-5.1.37-bin.jar
- 複製mysql-connector-java-5.1.37-bin.jar到項目的libs目錄下
- 右鍵–>Add As Library
- 註冊驅動
- 獲取數據庫連接對象 Connection
- 定義sql
- 獲取執行sql語句的對象 Statement
- 執行sql,接受返回結果
- 處理結果
- 釋放資源
代碼實現:
public class JDBCDemo {
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbase", "root", "root");
String sql = "update buyer set age=18 where id=103";
Statement statement = connection.createStatement();
int count = statement.executeUpdate(sql);
System.out.println(count);
statement.close();
connection.close();
}
}
3. 詳解各個對象:
1. DriverManager:驅動管理對象
- 功能:
- 註冊驅動:告訴程序該使用哪一個數據庫驅動jar
static void registerDriver(Driver driver) :註冊與給定的驅動程序 DriverManager 。
寫代碼使用: Class.forName(“com.mysql.jdbc.Driver”);
通過查看源碼發現:在com.mysql.jdbc.Driver類中存在靜態代碼塊
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
注意:mysql5之後的驅動jar包可以省略註冊驅動的步驟。
- 獲取數據庫連接:
- 方法:static Connection getConnection(String url, String user, String password)
- 參數:
- url:指定連接的路徑
- 語法:jdbc:mysql://ip地址(域名):端口號/數據庫名稱
- 例子:jdbc:mysql://localhost:3306/db3
- 細節:如果連接的是本機mysql服務器,並且mysql服務默認端口是3306,則url可以簡寫爲:jdbc:mysql:///數據庫名稱
- user:用戶名
- password:密碼
2. Connection:數據庫連接對象
- 功能:
- 獲取執行sql 的對象
- Statement createStatement()
- PreparedStatement prepareStatement(String sql)
- 管理事務:
- 開啓事務:void setAutoCommit(boolean autoCommit) :調用該方法設置參數爲false,即開啓事務
- 提交事務:void commit()
- 回滾事務:void rollback()
3. Statement:執行sql的對象
- 執行sql
- boolean execute(String sql) :可以執行任意的sql 瞭解
- int executeUpdate(String sql) :執行DML(insert、update、delete)語句、DDL(create,alter、drop)語句
- 返回值:影響的行數,可以通過這個影響的行數判斷DML語句是否執行成功 返回值>0的則執行成功,反之,則失敗。
- ResultSet executeQuery(String sql) :執行DQL(select)語句
- 練習:
- admin 表 添加一條記錄
- admin 表 修改記錄(代碼略)
- admin 表 刪除一條記錄(代碼略)
插入代碼:
public class JDBCDemo {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
//1. 註冊驅動
Class.forName("com.mysql.jdbc.Driver");
//2. 定義sql
String sql = "insert into admin values ('admin','admin5','normal')";
//3.獲取Connection對象
connection = DriverManager.getConnection("jdbc:mysql:///dbase", "root", "root");
//4.獲取執行sql的對象 Statement
statement = connection.createStatement();
//5.執行sql
int count = statement.executeUpdate(sql);
//5.執行sql
System.out.println(count);
if (count > 0) {
System.out.println("成功!!");
} else {
System.out.println("失敗~~~");
}
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
//7. 釋放資源
//避免空指針異常
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
結果:
1
成功!!
4. ResultSet:結果集對象,封裝查詢結果
- boolean next(): 遊標向下移動一行,判斷當前行是否是最後一行末尾(是否有數據),如果是,則返回false,如果不是則返回true
- getXxx(參數):獲取數據
- Xxx:代表數據類型 如: int getInt() , String getString()
- 參數:
- int:代表列的編號,從1開始 如: getString(1)
- String:代表列名稱。 如: getDouble(“balance”)
- 注意:
- 使用步驟:
- 遊標向下移動一行
- 判斷是否有數據
- 獲取數據
練習: 定義一個方法,查詢Orderitems表的數據將其封裝爲對象,然後裝載集合,返回。
1. 定義Orderitems 類:
package com.xzzz.domin;
public class Orderitems {
private int id;
private String orderid;
private int gid;
private String gname;
private double gprice;
private int count;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getOrderid() {
return orderid;
}
public void setOrderid(String orderid) {
this.orderid = orderid;
}
public int getGid() {
return gid;
}
public void setGid(int gid) {
this.gid = gid;
}
public String getGname() {
return gname;
}
public void setGname(String gname) {
this.gname = gname;
}
public double getGprice() {
return gprice;
}
public void setGprice(double gprice) {
this.gprice = gprice;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return "Orderitems{" +
"id=" + id +
", orderid='" + orderid + '\'' +
", gid=" + gid +
", gname='" + gname + '\'' +
", gprice=" + gprice +
", count=" + count +
'}';
}
}
2. 定義方法 public List<Emp> findAll(){}
3. 實現方法 select * from emp;
public class JDBCDemo {
public static void main(String[] args) throws SQLException {
JDBCDemo demo = new JDBCDemo();
List<Orderitems> list = demo.findAll();
System.out.println(list);
}
public List<Orderitems> findAll() throws SQLException {
List<Orderitems> list = new ArrayList<>();
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql:///dbase", "root", "root");
String sql = "select * from Orderitems";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
Orderitems oi = null;
//獲取數據
while (rs.next()) {
oi = new Orderitems();
oi.setId(rs.getInt("id"));
oi.setCount(rs.getInt("count"));
oi.setGid(rs.getInt("gid"));
oi.setOrderid(rs.getString("orderid"));
oi.setGname(rs.getString("gname"));
oi.setGprice(rs.getDouble("gprice"));
list.add(oi);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//7. 釋放資源
//避免空指針異常
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
if (rs!= null){
rs.close();
}
}
return list;
}
}
結果:
[Orderitems{id=10, orderid=‘2019-11-23-18-51-14-5114a004’, gid=1, gname=‘steam’, gprice=1.0, count=38}, Orderitems{id=11, orderid=‘2019-11-23-18-51-14-5114a004’, gid=6, gname=‘steam’, gprice=2.0, count=4}, Orderitems{id=12, orderid=‘2019-11-23-19-13-46-1346a006’, gid=5, gname=‘steam’, gprice=1.0, count=4}]
5. PreparedStatement:執行sql的對象
- SQL注入問題:在拼接sql時,有一些sql的特殊關鍵字參與字符串的拼接。會造成安全性問題
- 輸入用戶隨便,輸入密碼:a’ or ‘a’ = 'a
- sql:select * from user where username = ‘fhdsjkf’ and password = ‘a’ or ‘a’ = ‘a’
- 解決sql注入問題:使用PreparedStatement對象來解決
prepareStatement對象防止sql注入的方式是把用戶非法輸入的單引號用\反斜槓做了轉義,從而達到了防止sql注入的目的
- 預編譯的SQL:參數使用?作爲佔位符
- 步驟:
- 導入驅動jar包 mysql-connector-java-5.1.37-bin.jar
- 註冊驅動
- 獲取數據庫連接對象 Connection
- 定義sql
注意:sql的參數使用?作爲佔位符。 如:select * from user where username = ? and password = ?;- 獲取執行sql語句的對象 PreparedStatement Connection.prepareStatement(String sql)
- 給?賦值:
- 方法: setXxx(參數1,參數2)
- 參數1:?的位置編號 從1 開始
- 參數2:?的值
- 執行sql,接受返回結果,不需要傳遞sql語句
- 處理結果
- 釋放資源
- 注意:後期都會使用PreparedStatement來完成增刪改查的所有操作
1. 可以防止SQL注入
2. 效率更高
抽取JDBC工具類 : JDBCUtils
- 目的:簡化書寫
- 分析:
註冊驅動也抽取
抽取一個方法獲取連接對象
- 需求:不想傳遞參數(麻煩),還得保證工具類的通用性。
- 解決:配置文件
jdbc.properties
url=
user=
password=抽取一個方法釋放資源
代碼實現:
public class JDBCUtil {
private static String username;
private static String password;
private static String driver;
private static String url;
/**
* 文件的讀取,只需要讀取一次即可拿到這些值。使用靜態代碼塊
*/
static {
//1. 創建Properties集合類。
Properties pro = new Properties();
//獲取src路徑下的文件的方式--->ClassLoader 類加載器
ClassLoader cl = JDBCUtil.class.getClassLoader();
URL resource = cl.getResource("JDBC.properties");
String path = resource.getPath();
try {
//2. 加載文件
pro.load(new FileReader(path));
//3. 獲取數據,賦值
url = pro.getProperty("url");
username = pro.getProperty("username");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
//4. 註冊驅動
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 獲取連接
* @return 連接對象
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,username,password);
}
/**
* 釋放資源
* @param stmt
* @param con
*/
public static void close(Statement stmt,Connection con){
if (stmt!=null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Statement stmt, Connection con, ResultSet rs){
close(stmt,con);
if (rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
JDBC控制事務:
1. 事務:一個包含多個步驟的業務操作。如果這個業務操作被事務管理,則這多個步驟要麼同時成功,要麼同時失敗。
2. 操作:
1. 開啓事務
2. 提交事務
3. 回滾事務
4. 使用Connection對象來管理事務
開啓事務:setAutoCommit(boolean autoCommit) :調用該方法設置參數爲false,即開啓事務--------------(在執行sql之前開啓事務)
提交事務:commit() ----------(當所有sql都執行完提交事務)
回滾事務:rollback() ----------- 在catch中回滾事務
轉賬案例:
public class JDBCDemo {
public static void main(String[] args) {
Connection con = null;
PreparedStatement psrm1 = null;
PreparedStatement psrm2 = null;
try {
con = JDBCUtil.getConnection();
//開啓事務
con.setAutoCommit(false);
String sq1 = "update account set balance = balance - ? where id = ?";
String sq2 = "update account set balance = balance + ? where id = ?";
psrm1 = con.prepareStatement(sq1);
psrm2 = con.prepareStatement(sq2);
psrm1.setDouble(1, 500);
psrm1.setInt(2, 1);
// 手動製造異常
int i = 3 / 0;
psrm2.setDouble(1, 500);
psrm2.setInt(2, 2);
psrm1.executeUpdate();
psrm2.executeUpdate();
//開啓事務
con.commit();
} catch (Exception e) {
if (con != null) {
try {
//事務回滾
con.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();
} finally {
JDBCUtil.close(psrm1, null);
JDBCUtil.close(psrm2, con);
}
}
}
數據庫連接池
1. 概念:其實就是一個容器(集合),存放數據庫連接的容器。
當系統初始化好後,容器被創建,容器中會申請一些連接對象,當用戶來訪問數據庫時,從容器中獲取連接對象,用戶訪問完之後,會將連接對象歸還給容器。
2. 好處:
1. 節約資源
2. 用戶訪問高效
3. 實現:
1. 標準接口:DataSource javax.sql包下的
- 方法:
- 獲取連接:getConnection()
- 歸還連接:Connection.close()。如果連接對象Connection是從連接池中獲取的,那麼調用Connection.close()方法,則不會再關閉連接了。而是歸還連接
2. 一般我們不去實現它,有數據庫廠商來實現
- C3P0:數據庫連接池技術
- Druid:數據庫連接池實現技術,由阿里巴巴提供的
4. C3P0:數據庫連接池技術
步驟:
- 導入jar包 (兩個) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar ,
- 不要忘記導入數據庫驅動jar包
- 定義配置文件:
- 名稱: c3p0.properties 或者 c3p0-config.xml
- 路徑:直接將文件放在src目錄下即可。
- 創建核心對象 數據庫連接池對象 ComboPooledDataSource
- 獲取連接: getConnection
代碼:
//1.創建數據庫連接池對象
//沒有參數,使用默認配置
DataSource ds = new ComboPooledDataSource();
//2. 獲取連接對象
Connection conn = ds.getConnection();
配置文件:
<c3p0-config>
<!-- 使用默認的配置讀取連接池對象 -->
<default-config>
<!-- 連接參數 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/db4</property>
<property name="user">root</property>
<property name="password">root</property>
<!-- 連接池參數 -->
<!--初始化申請的連接數量-->
<property name="initialPoolSize">5</property>
<!--最大的連接數量-->
<property name="maxPoolSize">10</property>
<!--超時時間-->
<property name="checkoutTimeout">3000</property>
</default-config>
<named-config name="otherc3p0">
<!-- 連接參數 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/db3</property>
<property name="user">root</property>
<property name="password">root</property>
<!-- 連接池參數 -->
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">8</property>
<property name="checkoutTimeout">1000</property>
</named-config>
</c3p0-config>
5. Druid:數據庫連接池實現技術,由阿里巴巴提供的
1. 步驟:
- 導入jar包 druid-1.0.9.jar
- 定義配置文件:
- 是properties形式的
- 可以叫任意名稱,可以放在任意目錄下
- 加載配置文件。Properties
- 獲取數據庫連接池對象:通過工廠來來獲取 DruidDataSourceFactory
- 獲取連接:getConnection
2. 定義工具類
- 定義一個類 JDBCUtils
- 提供靜態代碼塊加載配置文件,初始化連接池對象
- 提供方法
- 獲取連接方法:通過數據庫連接池獲取連接
- 釋放資源
- 獲取連接池的方法
Druid操作代碼:
public class DataSourseDemo {
public static void main(String[] args) throws Exception {
//1.導入jar包
//2.定義配置文件
//3.加載配置文件
Properties pr = new Properties();
InputStream is = DataSourseDemo.class.getClassLoader().getResourceAsStream("druid.properties");
pr.load(is);
//4.獲取連接池對象
DataSource ds = new DruidDataSourceFactory().createDataSource(pr);
//5.獲取連接
Connection con = ds.getConnection();
System.out.println(con);
}
}
Spring JDBC
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:查詢結果,將結果封裝爲對象--------一般用於聚合函數的查詢
4. 練習:
查詢所有記錄,將其封裝爲User對象的List集合
@Test
public void test() {
String sql = "SELECT * from user";
List<User> query = template.query(sql, new BeanPropertyRowMapper<User>(User.class));
System.out.println(query);
}
結果:
[User{id=1, username=‘superbaby’, password=‘123’}, User{id=2, username=‘a001’, password=‘a001’}]
查詢總記錄數
@Test
public void test() {
String sql = "SELECT count(id) from user ";
Long aLong = template.queryForObject(sql, Long.class);
System.out.println(aLong);
}
結果:
2