JDBC:
1. 概念:Java DataBase Connectivity Java 數據庫鏈接, Java語言操做數據庫
* JDBC本質:實際上是官方(sun公司)定義的一套操做全部關係型數據庫的規則,即接口。各個數據庫廠商去實現這套接口,提供數據庫驅動jar包。咱們可使用這套接口(JDBC)編程,真正執行的代碼是驅動jar包中的實現類。
2. 快速入門:
* 步驟:
1. 導入驅動jar包 mysql-connector-java-5.1.37-bin.jar
1.複製mysql-connector-java-5.1.37-bin.jar到項目的libs目錄下
2.右鍵-->Add As Library
2. 註冊驅動
3. 獲取數據庫鏈接對象 Connection
4. 定義sql
5. 獲取執行sql語句的對象 Statement
6. 執行sql,接受返回結果
7. 處理結果
8. 釋放資源
* 代碼實現:
//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 = 500 where id = 1";
//5.獲取執行sql的對象 Statement
Statement stmt = conn.createStatement();
//6.執行sql
int count = stmt.executeUpdate(sql);
//7.處理結果
System.out.println(count);
//8.釋放資源
stmt.close();
conn.close();
3. 詳解各個對象:
1. DriverManager:驅動管理對象
* 功能:
1. 註冊驅動:告訴程序該使用哪個數據庫驅動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包能夠省略註冊驅動的步驟。
2. 獲取數據庫鏈接:
* 方法: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:數據庫鏈接對象
1. 功能:
1. 獲取執行sql 的對象
* Statement createStatement()
* PreparedStatement prepareStatement(String sql)
2. 管理事務:
* 開啓事務:void setAutoCommit(boolean autoCommit) :調用該方法設置參數爲false,即開啓事務
* 提交事務:void commit()
* 回滾事務:void rollback()
3. Statement:執行sql的對象
1. 執行sql
1. boolean execute(String sql) :能夠執行任意的sql 瞭解
2. int executeUpdate(String sql) :執行DML(insert、update、delete)語句、DDL(create,alter、drop)語句
* 返回值:影響的行數,能夠經過這個影響的行數判斷DML語句是否執行成功 返回值>0的則執行成功,反之,則失敗。
3. ResultSet executeQuery(String sql) :執行DQL(select)語句
2. 練習:
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();
}
}
}
4. ResultSet:結果集對象,封裝查詢結果
* boolean next(): 遊標向下移動一行,判斷當前行是不是最後一行末尾(是否有數據),若是是,則返回false,若是不是則返回true
* getXxx(參數):獲取數據
* Xxx:表明數據類型 如: int getInt() , String getString()
* 參數:
1. int:表明列的編號,從1開始 如: getString(1)
2. String:表明列名稱。 如: getDouble("balance")
* 注意:
* 使用步驟:
1. 遊標向下移動一行
2. 判斷是否有數據
3. 獲取數據
//循環判斷遊標是不是最後一行末尾。
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表的數據將其封裝爲對象,而後裝載集合,返回。
1. 定義Emp類
2. 定義方法 public List<Emp> findAll(){}
3. 實現方法 select * from emp;
5. PreparedStatement:執行sql的對象
1. SQL注入問題:在拼接sql時,有一些sql的特殊關鍵字參與字符串的拼接。會形成安全性問題
1. 輸入用戶隨便,輸入密碼:a' or 'a' = 'a
2. sql:select * from user where username = 'fhdsjkf' and password = 'a' or 'a' = 'a'
2. 解決sql注入問題:使用PreparedStatement對象來解決
3. 預編譯的SQL:參數使用?做爲佔位符
4. 步驟:
1. 導入驅動jar包 mysql-connector-java-5.1.37-bin.jar
2. 註冊驅動
3. 獲取數據庫鏈接對象 Connection
4. 定義sql
* 注意:sql的參數使用?做爲佔位符。 如:select * from user where username = ? and password = ?;
5. 獲取執行sql語句的對象 PreparedStatement Connection.prepareStatement(String sql)
6. 給?賦值:
* 方法: setXxx(參數1,參數2)
* 參數1:?的位置編號 從1 開始
* 參數2:?的值
7. 執行sql,接受返回結果,不須要傳遞sql語句
8. 處理結果
9. 釋放資源
5. 注意:後期都會使用PreparedStatement來完成增刪改查的全部操做
1. 能夠防止SQL注入
2. 效率更高
抽取JDBC工具類 : JDBCUtils
* 目的:簡化書寫
* 分析:
1. 註冊驅動也抽取
2. 抽取一個方法獲取鏈接對象
* 需求:不想傳遞參數(麻煩),還得保證工具類的通用性。
* 解決:配置文件
jdbc.properties
url=
user=
password=
3. 抽取一個方法釋放資源
* 代碼實現:
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();
}
}
}
}
* 練習:
* 需求:
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;
}
/**
* 登陸方法,使用PreparedStatement實現
*/
public boolean login2(String username ,String password){
if(username == null || password == null){
return false;
}
//鏈接數據庫判斷是否登陸成功
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
//1.獲取鏈接
try {
conn = JDBCUtil.getConnection();
//2.定義sql
String sql = "select * from user where username = ? and password = ?";
//3.獲取執行sql的對象
pstmt = conn.prepareStatement(sql);
//給?賦值
pstmt.setString(1,username);
pstmt.setString(2,password);
//4.執行查詢,不須要傳遞sql
rs = pstmt.executeQuery();
//5.判斷
/* if(rs.next()){//若是有下一行,則返回true
return true;
}else{
return false;
}*/
return rs.next();//若是有下一行,則返回true
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtil.closeResource(rs,pstmt,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);
}
}
}
JDBC數據庫鏈接池
數據庫鏈接池
1. 概念:其實就是一個容器(集合),存放數據庫鏈接的容器。
當系統初始化好後,容器被建立,容器中會申請一些鏈接對象,當用戶來訪問數據庫時,從容器中獲取鏈接對象,用戶訪問完以後,會將鏈接對象歸還給容器。
2. 好處:
1. 節約資源
2. 用戶訪問高效
3. 實現:
1. 標準接口:DataSource javax.sql包下的
1. 方法:
* 獲取鏈接:getConnection()
* 歸還鏈接:Connection.close()。若是鏈接對象Connection是從鏈接池中獲取的,那麼調用Connection.close()方法,則不會再關閉鏈接了。而是歸還鏈接
2. 通常咱們不去實現它,有數據庫廠商來實現
1. C3P0:數據庫鏈接池技術
2. Druid:數據庫鏈接池實現技術,由阿里巴巴提供的
4. C3P0:數據庫鏈接池技術
* 步驟:
1. 導入jar包 (三個) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar和mysql-connector-java-5.1.37-bin.jar
* 不要忘記導入數據庫驅動jar包
2. 定義配置文件:
* 名稱: c3p0.properties 或者 c3p0-config.xml
* 路徑:直接將文件放在src目錄下便可。
3. 建立核心對象 數據庫鏈接池對象 ComboPooledDataSource
4. 獲取鏈接: getConnection
* 代碼:
//1.建立數據庫鏈接池對象
DataSource ds = new ComboPooledDataSource();
//2. 獲取鏈接對象
Connection conn = ds.getConnection();
5. Druid:數據庫鏈接池實現技術,由阿里巴巴提供的
1. 步驟:
1. 導入jar包 druid-1.0.9.jar
2. 定義配置文件:
* 是properties形式的
* 能夠叫任意名稱,能夠放在任意目錄下
3. 加載配置文件。Properties
4. 獲取數據庫鏈接池對象:經過工廠來來獲取 DruidDataSourceFactory
5. 獲取鏈接:getConnection
* 代碼:
//3.加載配置文件
Properties pro = new Properties();
InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
//4.獲取鏈接池對象
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
//5.獲取鏈接
Connection conn = ds.getConnection();
2. 定義工具類
1. 定義一個類 JDBCUtils
2. 提供靜態代碼塊加載配置文件,初始化鏈接池對象
3. 提供方法
1. 獲取鏈接方法:經過數據庫鏈接池獲取鏈接
2. 釋放資源
3. 獲取鏈接池的方法
* 代碼:
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;
}
}
Spring JDBC:JDBCTemplat
* Spring框架對JDBC的簡單封裝。提供了一個JDBCTemplate對象簡化JDBC的開發
* 步驟:
1. 導入jar包,5個springjdbc的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. 練習:
* 需求:
1. 修改1號數據的 salary 爲 10000
2. 添加一條記錄
3. 刪除剛纔添加的記錄
4. 查詢id爲1的記錄,將其封裝爲Map集合
5. 查詢全部記錄,將其封裝爲List
6. 查詢全部記錄,將其封裝爲Emp對象的List集合。重要!!!!!
List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
7. 查詢總記錄數
* 代碼:
import cn.itcast.domain.Emp;
import cn.itcast.utils.JDBCUtils;
import org.junit.Test;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
public class JdbcTemplateDemo2 {
//Junit單元測試,可讓方法獨立執行
//1. 獲取JDBCTemplate對象
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
/**
* 1. 修改1號數據的 salary 爲 10000
*/
@Test
public void test1(){
//2. 定義sql
String sql = "update emp set salary = 10000 where id = 1001";
//3. 執行sql
int count = template.update(sql);
System.out.println(count);
}
/**
* 2. 添加一條記錄
*/
@Test
public void test2(){
String sql = "insert into emp(id,ename,dept_id) values(?,?,?)";
int count = template.update(sql, 1015, "郭靖", 10);
System.out.println(count);
}
/**
* 3.刪除剛纔添加的記錄
*/
@Test
public void test3(){
String sql = "delete from emp where id = ?";
int count = template.update(sql, 1015);
System.out.println(count);
}
/**
* 4.查詢id爲1001的記錄,將其封裝爲Map集合
* 注意:這個方法查詢的結果集長度只能是1
*/
@Test
public void test4(){
String sql = "select * from emp where id = ? or id = ?";
Map<String, Object> map = template.queryForMap(sql, 1001,1002);
System.out.println(map);
//{id=1001, ename=孫悟空, job_id=4, mgr=1004, joindate=2000-12-17, salary=10000.00, bonus=null, dept_id=20}
}
/**
* 5. 查詢全部記錄,將其封裝爲List
*/
@Test
public void test5(){
String sql = "select * from emp";
List<Map<String, Object>> list = template.queryForList(sql);
for (Map<String, Object> stringObjectMap : list) {
System.out.println(stringObjectMap);
}
}
/**
* 6. 查詢全部記錄,將其封裝爲Emp對象的List集合
*/
@Test
public void test6(){
String sql = "select * from emp";
List<Emp> list = template.query(sql, new RowMapper<Emp>() {
@Override
public Emp mapRow(ResultSet rs, int i) throws SQLException {
Emp emp = new Emp();
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.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);
return emp;
}
});
for (Emp emp : list) {
System.out.println(emp);
}
}
/**
* 6. 查詢全部記錄,將其封裝爲Emp對象的List集合
*/
@Test
public void test6_2(){
String sql = "select * from emp";
List<Emp> list = template.query(sql, new BeanPropertyRowMapper<Emp>(Emp.class));
for (Emp emp : list) {
System.out.println(emp);
}
}
/**
* 7. 查詢總記錄數
*/
@Test
public void test7(){
String sql = "select count(id) from emp";
Long total = template.queryForObject(sql, Long.class);
System.out.println(total);
}
}