JDBC概念
JAVA Database Connectivity java 數據庫連接
爲什麼會出現JDBC
SUN公司提供的一種數據庫訪問規則、規範, 由於數據庫種類較多,並且java語言使用比較廣泛,sun公司就提供了一種規範,讓其他的數據庫提供商去實現底層的訪問規則。 我們的java程序只要使用sun公司提供的jdbc驅動即可。
使用JDBC的基本步驟
-
註冊驅動
在工程中新建lib文件夾,將驅動copy到此文件夾,並右鍵點擊構建路徑
Class.forName(“com.mysql.jdbc.Driver()”) -
建立連接
//DriverManager.getConnection(“jdbc:mysql://localhost/test?user=monty&password=greatsqldb”);
//2. 建立連接 參數一: 協議 + 訪問的數據庫 , 參數二: 用戶名 , 參數三: 密碼。
conn = DriverManager.getConnection(“jdbc:mysql://localhost/student”, “root”, “root”);
- 創建statement
//3. 創建sql對象
st = conn.createStatement();
- 執行sql ,得到ResultSet
//4. 執行查詢 , 得到結果集
String sql = “select * from t_stu”;
rs = st.executeQuery(sql);
// 如果是要更新數據庫,則使用executeUpdate
String sql = "update account set balance = 500 where id = 1";
rs = st.executeUpdate(sql);
- 遍歷結果集
//5. 遍歷查詢每一條記錄
while(rs.next()){
int id = rs.getInt(“id”);
String name = rs.getString(“name”);
int age = rs.getInt(“age”);
System.out.println(“id=”+id + “===name=”+name+"==age="+age);
}
釋放資源
private static void closeRs(ResultSet rs) {
try {
if(rs!=null) {
rs.close();
}
}catch(SQLException e) {
e.printStackTrace();
}finally {
rs=null;
}
}
private static void closeSt(Statement st) {
try {
if(st!=null) {
st.close();
}
}catch(SQLException e) {
e.printStackTrace();
}finally {
st=null;
}
}
private static void closeConn(Connection conn) {
try {
if(conn!=null) {
conn.close();
}
}catch(SQLException e) {
e.printStackTrace();
}finally {
conn=null;
}
}
詳解各個對象
- DriverManager: 驅動管理對象
- 功能 :
- 註冊驅動: 告訴程序該使用哪一個數據庫驅動包
- static void registerDriver(Driver driver):註冊與給定的驅動程序 DriverManager
寫代碼時使用Class.forName(“com.mysql.jdbc.Driver”);
通過源碼發現: 發現 com.mysql.jdbc.Driver 類中有註冊驅動的靜態代碼塊 - 獲取數據庫連接:
- 方法: static Connection getConnection(String url,String user,String password)
- 參數:
- url : 指定連接的路徑
- 語法: jdbc:mysql://ip地址(域名):端口號/數據庫名稱
- 例子: jdbc:mysql://localhost:3306/db3
- 細節: 如果連接的是本機mysql服務器,並且mysql服務默認服務端口是3306,則可以簡寫爲 jdbc:mysql:///數據庫名稱
- user: 用戶名
- password: 密碼
- url : 指定連接的路徑
- static void registerDriver(Driver driver):註冊與給定的驅動程序 DriverManager
- 註冊驅動: 告訴程序該使用哪一個數據庫驅動包
- 功能 :
- Connection: 數據庫連接對象
- 功能:
- 獲取sql對象 的對象
- Statement createStatement();
- PrepareStatement prepareStatement(String sql);
- 獲取sql對象 的對象
- 管理事務:
- 開啓事務: void setAutoCommit(boolean autoCommit) : 調用該方法,設置參數爲false,
- 提交事務
- 回滾事務
- 功能:
- 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)語句
- 返回值:影響的行數,可以通過這個影響的行數判斷DML語句是否執行成功 返回值>0的則執行成功,反之,則失敗。
-
練習:
1. account表 添加一條記錄
2. account表 修改記錄
3. account表 刪除一條記錄代碼:
-
Statement stmt = null;
Connection conn = null;
try {
//1. 註冊驅動
Class.forName("com.mysql.jdbc.Driver");
//2. 定義sql
String sql = "insert into account values(null,'王五',3000)";
//3.獲取Connection對象
conn = DriverManager.getConnection("jdbc:mysql:///db3", "root", "root");
//4.獲取執行sql的對象 Statement
stmt = conn.createStatement();
//5.執行sql
int count = stmt.executeUpdate(sql);//影響的行數
//6.處理結果
System.out.println(count);
if(count > 0){
System.out.println("添加成功!");
}else{
System.out.println("添加失敗!");
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
//stmt.close();
//7. 釋放資源
//避免空指針異常
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- ResultSet:結果集對象,封裝查詢結果
- boolean next(): 遊標向下移動一行,判斷當前行是否是最後一行末尾(是否有數據),如果是,則返回false,如果不是則返回true
- getXxx(參數):獲取數據
-
Xxx:代表數據類型 如: int getInt() , String getString()
-
參數:
1. int:代表列的編號,從1開始 如: getString(1)
2. String:代表列名稱。 如: getDouble(“balance”) -
注意:
- 使用步驟:
- 遊標向下移動一行
- 判斷是否有數據
- 獲取數據
- 使用步驟:
-
//循環判斷遊標是否是最後一行末尾。
while(rs.next()){
//獲取數據
//6.2 獲取數據
int id = rs.getInt(1);
String name = rs.getString("name");
double balance = rs.getDouble(3);
System.out.println(id + "---" + name + "---" + balance);
}
-
練習:
- 定義一個方法,查詢emp表的數據將其封裝爲對象,然後裝載集合,返回。
- 定義Emp類
- 定義方法 public List findAll(){}
- 實現方法 select * from emp;
Emp
- 定義一個方法,查詢emp表的數據將其封裝爲對象,然後裝載集合,返回。
package domain;
import java.util.Date;
/*
* 查詢emp表的數據並將其封裝爲對象
* 1. 定義emp類
* 2. 定義方法 public List<Emp> findAll(){}
* 3. 實現方法 select * from emp;
*
* 封裝emp數據的JavaBean
*/
public class Emp {
private int id;
private String ename;
private int job_id;
private int mgr;
private Date joindate;
private double salary;
private double bonus;
private int dept_id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public int getJob_id() {
return job_id;
}
public void setJob_id(int job_id) {
this.job_id = job_id;
}
public int getMgr() {
return mgr;
}
public void setMgr(int mgr) {
this.mgr = mgr;
}
public Date getJoindate() {
return joindate;
}
public void setJoindate(Date joindate) {
this.joindate = joindate;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getBonus() {
return bonus;
}
public void setBonus(double bonus) {
this.bonus = bonus;
}
public int getDept_id() {
return dept_id;
}
public void setDept_id(int dept_id) {
this.dept_id = dept_id;
}
@Override
public String toString() {
return "Emp [id=" + id + ", ename=" + ename + ", job_id=" + job_id + ", mgr=" + mgr + ", joindate="
+ joindate + ", salary=" + salary + ", bonus=" + bonus + ", dept_id=" + dept_id + "]";
}
}
定義方法
package itcast;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import domain.Emp;
/*
* 查詢emp表的數據並將其封裝爲對象
* 1. 定義emp類
* 2. 定義方法 public List<Emp> findAll(){}
* 3. 實現方法 select * from emp;
*/
public class SelectTest {
public static void main(String[] args) {
List<Emp> list = new SelectTest().findAll();
System.out.println(list);
System.out.println(list.size());
}
public List<Emp> findAll(){
List<Emp> list = null;
Connection conn = null;
Statement stmt =null;
ResultSet rs = null;
// 註冊驅動
try {
Class.forName("com.mysql.jdbc.Driver");
// 獲取連接
try {
conn = DriverManager.getConnection("jdbc:mysql:///db3","root","root");
String sql = "select * from emp";
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
// 便利結果集 封裝對象 莊子啊集合
Emp emp = new Emp();
list = new ArrayList<>();
while(rs.next()) {
// 獲取數據
int id = rs.getInt("id");
String ename = rs.getString("ename");
int job_id = rs.getInt("job_id");
int mgr = rs.getInt("mgr");
Date joindate = rs.getDate("joindate");
double salary = rs.getDouble("salary");
double bonus = rs.getDouble("bonus");
int dept_id = rs.getInt("dept_id");
// 創建emp對象,並賦值
emp.setId(id);
emp.setEname(ename);
emp.setJob_id(job_id);
emp.setMgr(mgr);
emp.setJoindate(joindate);
emp.setSalary(salary);
emp.setBonus(bonus);
emp.setDept_id(dept_id);
// 裝載集合
list.add(emp);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(rs!=null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(stmt!=null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(conn!=null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return list;
}
}
- PreparedStatement:執行sql的對象
-
SQL注入問題:在拼接sql時,有一些sql的特殊關鍵字參與字符串的拼接。會造成安全性問題
- 輸入用戶隨便,輸入密碼:a’ or ‘a’ = 'a
- sql:select * from user where username = ‘fhdsjkf’ and password = ‘a’ or ‘a’ = ‘a’
-
解決sql注入問題:使用PreparedStatement對象來解決
-
預編譯的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:?的值
- 方法: setXxx(參數1,參數2)
- 執行sql,接受返回結果,不需要傳遞sql語句
- 處理結果
- 釋放資源
-
注意:後期都會使用PreparedStatement來完成增刪改查的所有操作
- 可以防止SQL注入
- 效率更高
-
抽取JDBC工具類 : JDBCUtils
-
目的:簡化書寫
-
分析:
-
註冊驅動也抽取
-
抽取一個方法獲取連接對象
- 需求:不想傳遞參數(麻煩),還得保證工具類的通用性。
- 解決:配置文件
jdbc.properties
url=
user=
password=
-
抽取一個方法釋放資源
- 代碼實現:
-
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
/**
* 文件的讀取,只需要讀取一次即可拿到這些值。使用靜態代碼塊
*/
static{
//讀取資源文件,獲取值。
try {
//1. 創建Properties集合類。
Properties pro = new Properties();
//獲取src路徑下的文件的方式--->ClassLoader 類加載器
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
URL res = classLoader.getResource("jdbc.properties");
String path = res.getPath();
System.out.println(path);///D:/IdeaProjects/itcast/out/production/day04_jdbc/jdbc.properties
//2. 加載文件
// pro.load(new FileReader("D:\\IdeaProjects\\itcast\\day04_jdbc\\src\\jdbc.properties"));
pro.load(new FileReader(path));
//3. 獲取數據,賦值
url = pro.getProperty("url");
user = pro.getProperty("user");
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, user, password);
}
/**
* 釋放資源
* @param stmt
* @param conn
*/
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();
}
}
}
/**
* 釋放資源
* @param stmt
* @param 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();
}
}
}
}
jdbc.properties
url=jdbc:mysql:///db3
user=root
password=root
driver=com.mysql.jdbc.Driver
* 練習:
* 需求:
1. 通過鍵盤錄入用戶名和密碼
2. 判斷用戶是否登錄成功
* select * from user where username = "" and password = "";
* 如果這個sql有查詢結果,則成功,反之,則失敗
* 步驟:
1. 創建數據庫表 user
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32),
PASSWORD VARCHAR(32)
);
INSERT INTO USER VALUES(NULL,'zhangsan','123');
INSERT INTO USER VALUES(NULL,'lisi','234');
2. 代碼實現:
public class JDBCDemo9 {
public static void main(String[] args) {
//1.鍵盤錄入,接受用戶名和密碼
Scanner sc = new Scanner(System.in);
System.out.println("請輸入用戶名:");
String username = sc.nextLine();
System.out.println("請輸入密碼:");
String password = sc.nextLine();
//2.調用方法
boolean flag = new JDBCDemo9().login(username, password);
//3.判斷結果,輸出不同語句
if(flag){
//登錄成功
System.out.println("登錄成功!");
}else{
System.out.println("用戶名或密碼錯誤!");
}
}
/**
* 登錄方法
*/
public boolean login(String username ,String password){
if(username == null || password == null){
return false;
}
//連接數據庫判斷是否登錄成功
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
//1.獲取連接
try {
conn = JDBCUtils.getConnection();
//2.定義sql
String sql = "select * from user where username = '"+username+"' and password = '"+password+"' ";
//3.獲取執行sql的對象
stmt = conn.createStatement();
//4.執行查詢
rs = stmt.executeQuery(sql);
//5.判斷
/* if(rs.next()){//如果有下一行,則返回true
return true;
}else{
return false;
}*/
return rs.next();//如果有下一行,則返回true
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(rs,stmt,conn);
}
return false;
}
}
JDBC控制事務:
1. 事務:一個包含多個步驟的業務操作。如果這個業務操作被事務管理,則這多個步驟要麼同時成功,要麼同時失敗。
2. 操作:
1. 開啓事務
2. 提交事務
3. 回滾事務
3. 使用Connection對象來管理事務
* 開啓事務:setAutoCommit(boolean autoCommit) :調用該方法設置參數爲false,即開啓事務
* 在執行sql之前開啓事務
* 提交事務:commit()
* 當所有sql都執行完提交事務
* 回滾事務:rollback()
* 在catch中回滾事務
4. 代碼:
public class JDBCDemo10 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
try {
//1.獲取連接
conn = JDBCUtils.getConnection();
//開啓事務
conn.setAutoCommit(false);
//2.定義sql
//2.1 張三 - 500
String sql1 = "update account set balance = balance - ? where id = ?";
//2.2 李四 + 500
String sql2 = "update account set balance = balance + ? where id = ?";
//3.獲取執行sql對象
pstmt1 = conn.prepareStatement(sql1);
pstmt2 = conn.prepareStatement(sql2);
//4. 設置參數
pstmt1.setDouble(1,500);
pstmt1.setInt(2,1);
pstmt2.setDouble(1,500);
pstmt2.setInt(2,2);
//5.執行sql
pstmt1.executeUpdate();
// 手動製造異常
int i = 3/0;
pstmt2.executeUpdate();
//提交事務
conn.commit();
} catch (Exception e) {
//事務回滾
try {
if(conn != null) {
conn.rollback();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
JDBCUtils.close(pstmt1,conn);
JDBCUtils.close(pstmt2,null);
}
}
}