mvc
JDBC:Java DataBase Connectivity Java 數(shù)據(jù)庫連接恕刘, Java語言操作數(shù)據(jù)庫 屈尼。JDBC本質(zhì):其實(shí)是官方(sun公司)定義的一套操作所有關(guān)系型數(shù)據(jù)庫的規(guī)則,即接口躬充。各個(gè)數(shù)據(jù)庫廠商去實(shí)現(xiàn)這套接口逃顶,提供數(shù)據(jù)庫驅(qū)動(dòng)jar包讨便。我們可以使用這套接口(JDBC)編程,真正執(zhí)行的代碼是驅(qū)動(dòng)jar包中的實(shí)現(xiàn)類以政。
快速入門:
- 步驟:
1霸褒、導(dǎo)入驅(qū)動(dòng)jar包 mysql-connector-java-5.1.37-bin.jar
1.1.復(fù)制mysql-connector-java-5.1.37-bin.jar 到項(xiàng)目的libs目錄下
1.2右鍵-->Add As Library
2、注冊(cè)驅(qū)動(dòng)
3盈蛮、獲取數(shù)據(jù)庫連接對(duì)象 Connection
4废菱、定義sql
5、獲取執(zhí)行sql語句的對(duì)象 Statement
6抖誉、執(zhí)行sql殊轴,接受返回結(jié)果
7、處理結(jié)果
8袒炉、釋放資源 - 代碼實(shí)現(xiàn)
public class JDBCDemo1 {
public static void main(String[] args) throws Exception{
//1. 導(dǎo)入驅(qū)動(dòng)jar包
//2.注冊(cè)驅(qū)動(dòng)
Class.forName("com.mysql.jdbc.Driver");
//3.獲取數(shù)據(jù)庫連接對(duì)象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/info", "root", "root");
//4.定義sql語句
String sql = "update account set balance = 500 where id = 1";
//5.獲取執(zhí)行sql的對(duì)象 Statement
Statement stmt = conn.createStatement();
//6.執(zhí)行sql
int count = stmt.executeUpdate(sql);
//7.處理結(jié)果
System.out.println(count);
//8.釋放資源
stmt.close();
conn.close();
}
}
詳解各個(gè)對(duì)象
1旁理、DriverManager:驅(qū)動(dòng)管理對(duì)象
- 功能:
1.注冊(cè)驅(qū)動(dòng):告訴程序該使用哪一個(gè)數(shù)據(jù)庫驅(qū)動(dòng)jar
static void registerDriver(Driver driver) :注冊(cè)與給定的驅(qū)動(dòng)程序 DriverManager 。
寫代碼使用: Class.forName("com.mysql.jdbc.Driver");
通過查看源碼發(fā)現(xiàn):在com.mysql.jdbc.Driver類中存在靜態(tài)代碼塊
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
注意:mysql5之后的驅(qū)動(dòng)jar包可以省略注冊(cè)驅(qū)動(dòng)的步驟我磁。
2.獲取數(shù)據(jù)庫連接:
- 方法:static Connection getConnection(String url, String user, String password)
- 參數(shù):
- url:指定連接的路徑
- 語法:jdbc:mysql://ip地址(域名):端口號(hào)/數(shù)據(jù)庫名稱
- 例子:jdbc:mysql://localhost:3306/db3
- 細(xì)節(jié):如果連接的是本機(jī)mysql服務(wù)器孽文,并且mysql服務(wù)默認(rèn)端口是3306,則url可以簡寫為:jdbc:mysql:///數(shù)據(jù)庫名稱
- user:用戶名
- password:密碼
2夺艰、Connection:數(shù)據(jù)庫連接對(duì)象
3.功能:
4.獲取執(zhí)行sql 的對(duì)象 - Statement createStatement()
- PreparedStatementprepareStatement(String sql)
2.管理事務(wù): - 開啟事務(wù):setAutoCommit(boolean autoCommit) :調(diào)用該方法設(shè)置參數(shù)為false芋哭,即開啟事務(wù)
- 提交事務(wù):commit()
- 回滾事務(wù):rollback()
3.Statement:執(zhí)行sql的對(duì)象
4.執(zhí)行sql
5.boolean execute(String sql) :可以執(zhí)行任意的sql 了解
6.int executeUpdate(String sql) :執(zhí)行DML(insert、update郁副、delete)語句减牺、DDL(create,alter霞势、drop)語句
- url:指定連接的路徑
- 返回值:影響的行數(shù)烹植,可以通過這個(gè)影響的行數(shù)判斷DML語句是否執(zhí)行成功 返回值>0的則執(zhí)行成功,反之愕贡,則失敗草雕。
3.ResultSet executeQuery(String sql) :執(zhí)行DQL(select)語句
4.練習(xí):
5.account表 添加一條記錄
6.account表 修改記錄
7.account表 刪除一條記錄
代碼:
public class JDBCDemo2 {
public static void main(String[] args) {
Statement stmt = null;
Connection conn = null;
try {
//1. 注冊(cè)驅(qū)動(dòng)
Class.forName("com.mysql.jdbc.Driver");
//2. 定義sql
String sql = "insert into account values('王五',null,3000)";
String sql = "update account set balance = 1 where id = 2";
String sql = "delete from account where id = 2";
//3.獲取Connection對(duì)象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/info", "root", "root");
//4.獲取執(zhí)行sql的對(duì)象 Statement
stmt = conn.createStatement();
//5.執(zhí)行sql
int count = stmt.executeUpdate(sql);//影響的行數(shù)
//6.處理結(jié)果
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:結(jié)果集對(duì)象,封裝查詢結(jié)果
- boolean next(): 游標(biāo)向下移動(dòng)一行,判斷當(dāng)前行是否是最后一行末尾(是否有數(shù)據(jù))憨琳,如果是诫钓,則返回false,如果不是則返回true
- getXxx(參數(shù)):獲取數(shù)據(jù)
- Xxx:代表數(shù)據(jù)類型 如: int getInt() , String getString()
- 參數(shù):
1.int:代表列的編號(hào),從1開始 如: getString(1)
2.String:代表列名稱篙螟。 如:getDouble("balance")
- 注意:
- 使用步驟:
1.游標(biāo)向下移動(dòng)一行
2.判斷是否有數(shù)據(jù)
3.獲取數(shù)據(jù)
- 使用步驟:
//循環(huán)判斷游標(biāo)是否是最后一行末尾菌湃。
while(rs.next()){
//獲取數(shù)據(jù)
//6.2 獲取數(shù)據(jù)
int id = rs.getInt(1);
String name = rs.getString("name");
double balance = rs.getDouble(3);
System.out.println(id + "---" + name + "---" + balance);
}
- 練習(xí):
- 定義一個(gè)方法,查詢emp表的數(shù)據(jù)將其封裝為對(duì)象遍略,然后裝載集合惧所,返回骤坐。
1.定義Emp類
2.定義方法 public List<Emp> findAll(){}
3.實(shí)現(xiàn)方法 select * from emp;
4.PreparedStatement:執(zhí)行sql的對(duì)象
5.SQL注入問題:在拼接sql時(shí),有一些sql的特殊關(guān)鍵字參與字符串的拼接下愈。會(huì)造成安全性問題
1.輸入用戶隨便纽绍,輸入密碼:a' or 'a' = 'a
2.sql:select * from user where username = 'fhdsjkf' and password = 'a' or 'a' = 'a'
6.解決sql注入問題:使用PreparedStatement對(duì)象來解決
7.預(yù)編譯的SQL:參數(shù)使用?作為占位符
8.步驟:
1.導(dǎo)入驅(qū)動(dòng)jar包 mysql-connector-java-5.1.37-bin.jar
2.注冊(cè)驅(qū)動(dòng)- 獲取數(shù)據(jù)庫連接對(duì)象 Connection
4.定義sql
- 注意:sql的參數(shù)使用?作為占位符势似。 如:select * from user where username = ? and password = ?;
- 獲取執(zhí)行sql語句的對(duì)象 PreparedStatement Connection.prepareStatement(String sql)
6.給拌夏?賦值:
- 方法: setXxx(參數(shù)1,參數(shù)2)
- 參數(shù)1:?的位置編號(hào) 從1 開始
- 參數(shù)2:履因?的值
- 執(zhí)行sql障簿,接受返回結(jié)果,不需要傳遞sql語句
- 處理結(jié)果
- 釋放資源
9.注意:后期都會(huì)使用PreparedStatement來完成增刪改查的所有操作
1.可以防止SQL注入
2.效率更高
- 獲取數(shù)據(jù)庫連接對(duì)象 Connection
抽取JDBC工具類 : JDBCUtils
- 目的:簡化書寫
- 分析:
1.注冊(cè)驅(qū)動(dòng)也抽取
2.抽取一個(gè)方法獲取連接對(duì)象- 需求:不想傳遞參數(shù)(麻煩)搓逾,還得保證工具類的通用性卷谈。
- 解決:配置文件
jdbc.properties
url=
user=
password=
3.抽取一個(gè)方法釋放資源
4.Druid:數(shù)據(jù)庫連接池實(shí)現(xiàn)技術(shù),由阿里巴巴提供的
1.步驟:
1.導(dǎo)入jar包 druid-1.0.9.jar
2.定義配置文件:
- 是properties形式的
- 可以叫任意名稱霞篡,可以放在任意目錄下- 加載配置文件世蔗。Properties
- 獲取數(shù)據(jù)庫連接池對(duì)象:通過工廠來來獲取 DruidDataSourceFactory
5.獲取連接:getConnection
- 代碼:
//3.加載配置文件
Properties pro = new Properties();
InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
//4.獲取連接池對(duì)象
DataSource ds = DruidDataSourceFactory.createDataSource(pro);
//5.獲取連接
Connection conn = ds.getConnection();
2.定義工具類
1.定義一個(gè)類 JDBCUtils
2.提供靜態(tài)代碼塊加載配置文件,初始化連接池對(duì)象
3.提供方法
1.獲取連接方法:通過數(shù)據(jù)庫連接池獲取連接
2.釋放資源
3.獲取連接池的方法 - 代碼實(shí)現(xiàn):
package com.neusoft.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* Druid連接池的工具類
*/
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
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/info
username=root
password=root
# 初始化連接數(shù)量
initialSize=5
# 最大連接數(shù)
maxActive=10
# 最大等待時(shí)間
maxWait=3000
JDBC查詢
public class JDBCDemo6 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1. 注冊(cè)驅(qū)動(dòng)
Class.forName("com.mysql.jdbc.Driver");
//2.獲取連接對(duì)象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/info", "root", "root");
//3.定義sql
String sql = "select * from account";
//4.獲取執(zhí)行sql對(duì)象
stmt = conn.createStatement();
//5.執(zhí)行sql
rs = stmt.executeQuery(sql);
//6.處理結(jié)果
//6.1 讓游標(biāo)向下移動(dòng)一行
rs.next();
//6.2 獲取數(shù)據(jù)
int id = rs.getInt(2);
String name = rs.getString("name");
double balance = rs.getDouble(3);
System.out.println(id + "---" + name + "---" + balance);
//6.1 讓游標(biāo)向下移動(dòng)一行
rs.next();
//6.2 獲取數(shù)據(jù)
int id2 = rs.getInt(2);
String name2 = rs.getString("name");
double balance2 = rs.getDouble(3);
System.out.println(id2 + "---" + name2 + "---" + balance2);
//6.1 讓游標(biāo)向下移動(dòng)一行
rs.next();
//6.2 獲取數(shù)據(jù)
int id3 = rs.getInt(2);
String name3 = rs.getString("name");
double balance3 = rs.getDouble(3);
System.out.println(id3 + "---" + name3 + "---" + balance3);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//7.釋放資源
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();
}
}
}
}
}
改寫成循環(huán)
package com.neusoft.jdbc1;
import java.sql.*;
public class JDBCDemo7 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1. 注冊(cè)驅(qū)動(dòng)
Class.forName("com.mysql.jdbc.Driver");
//2.獲取連接對(duì)象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/info", "root", "root");
//3.定義sql
String sql = "select * from account";
//4.獲取執(zhí)行sql對(duì)象
stmt = conn.createStatement();
//5.執(zhí)行sql
rs = stmt.executeQuery(sql);
//6.處理結(jié)果
//循環(huán)判斷游標(biāo)是否是最后一行末尾朗兵。
while(rs.next()){
//獲取數(shù)據(jù)
//6.2 獲取數(shù)據(jù)
int id = rs.getInt(2);
String name = rs.getString("name");
double balance = rs.getDouble(3);
System.out.println(id + "---" + name + "---" + balance);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//7.釋放資源
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();
}
}
}
}
}
分別使用普通方法和連接池進(jìn)行查詢emp
domain通常就代表了與數(shù)據(jù)庫表--一一對(duì)應(yīng)的javaBean
private Integer id;
private String ename;
private String job;
private Integer mgr;
private Date hiredate;
private int salary;
private int bonus;
private Integer deptno;
package com.neusoft.jdbc1;
import com.neusoft.domain.Emp;
import com.neusoft.utils.JDBCUtils;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
* * 定義一個(gè)方法污淋,查詢emp表的數(shù)據(jù)將其封裝為對(duì)象,然后裝載集合余掖,返回寸爆。
*/
public class JDBCDemo8 {
public static void main(String[] args) {
// List<Emp> list = new JDBCDemo8().findAll();
List<Emp> list = new JDBCDemo8().findAll2();
System.out.println(list);
System.out.println(list.size());
}
/**
* 查詢所有emp對(duì)象
* @return
*/
public List<Emp> findAll(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
List<Emp> list = null;
try {
//1.注冊(cè)驅(qū)動(dòng)
Class.forName("com.mysql.jdbc.Driver");
//2.獲取連接
conn = DriverManager.getConnection("jdbc:mysql:///info", "root", "root");
//3.定義sql
String sql = "select * from emp";
//4.獲取執(zhí)行sql的對(duì)象
stmt = conn.createStatement();
//5.執(zhí)行sql
rs = stmt.executeQuery(sql);
//6.遍歷結(jié)果集,封裝對(duì)象盐欺,裝載集合
Emp emp = null;
list = new ArrayList<Emp>();
while(rs.next()){
//獲取數(shù)據(jù)
int id = rs.getInt("empno");
String ename = rs.getString("ename");
String job = rs.getString("job");
int mgr = rs.getInt("mgr");
Date hiredate = rs.getDate("HIREDATE");
int salary = rs.getInt("sal");
int bonus = rs.getInt("comm");
int deptno = rs.getInt("deptno");
// 創(chuàng)建emp對(duì)象,并賦值
emp = new Emp();
emp.setId(id);
emp.setEname(ename);
emp.setJob(job);
emp.setMgr(mgr);
emp.setHiredate(hiredate);
emp.setSalary(salary);
emp.setBonus(bonus);
emp.setDeptno(deptno);
//裝載集合
list.add(emp);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
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();
}
}
}
return list;
}
/**
* 演示JDBC工具類
* @return
*/
public List<Emp> findAll2(){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
List<Emp> list = null;
try {
conn = JDBCUtils.getConnection();
//3.定義sql
String sql = "select * from emp";
//4.獲取執(zhí)行sql的對(duì)象
stmt = conn.createStatement();
//5.執(zhí)行sql
rs = stmt.executeQuery(sql);
//6.遍歷結(jié)果集赁豆,封裝對(duì)象,裝載集合
Emp emp = null;
list = new ArrayList<Emp>();
while(rs.next()){
int id = rs.getInt("empno");
String ename = rs.getString("ename");
String job = rs.getString("job");
int mgr = rs.getInt("mgr");
Date hiredate = rs.getDate("HIREDATE");
int salary = rs.getInt("sal");
int bonus = rs.getInt("comm");
int deptno = rs.getInt("deptno");
// 創(chuàng)建emp對(duì)象,并賦值
emp = new Emp();
emp.setId(id);
emp.setEname(ename);
emp.setJob(job);
emp.setMgr(mgr);
emp.setHiredate(hiredate);
emp.setSalary(salary);
emp.setBonus(bonus);
emp.setDeptno(deptno);
//裝載集合
list.add(emp);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(rs,stmt,conn);
}
return list;
}
}
SQL注入
SQL注入是比較常見的網(wǎng)絡(luò)攻擊方式之一冗美,它不是利用操作系統(tǒng)的BUG來實(shí)現(xiàn)攻擊魔种,而是針對(duì)程序員編寫時(shí)的疏忽,通過SQL語句粉洼,實(shí)現(xiàn)無賬號(hào)登錄节预,甚至篡改數(shù)據(jù)庫。
select * from user where username = 'OR 1=1 -- and password= ';
這個(gè)條件一定會(huì)成功
select * from user where username = ' ; Drop Database java9 -- and password= ';
怎么解決sql注入
- 練習(xí):
- 需求:
1.通過鍵盤錄入用戶名和密碼
2.判斷用戶是否登錄成功- select * from user where username = "" and password = "";
- 如果這個(gè)sql有查詢結(jié)果属韧,則成功安拟,反之,則失敗
- 步驟:
1.創(chuàng)建數(shù)據(jù)庫表 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');
package com.neusoft.jdbc1;
import com.neusoft.utils.JDBCUtils;
import java.sql.*;
import java.util.Scanner;
/**
* 練習(xí):
* * 需求:
* 1. 通過鍵盤錄入用戶名和密碼
* 2. 判斷用戶是否登錄成功
*/
public class JDBCDemo9 {
public static void main(String[] args) {
//1.鍵盤錄入宵喂,接受用戶名和密碼
Scanner sc = new Scanner(System.in);
System.out.println("請(qǐng)輸入用戶名:");
String username = sc.nextLine();
System.out.println("請(qǐng)輸入密碼:");
String password = sc.nextLine();
//2.調(diào)用方法
boolean flag = new JDBCDemo9().login2(username, password);
//3.判斷結(jié)果糠赦,輸出不同語句
if(flag){
//登錄成功
System.out.println("登錄成功!");
}else{
System.out.println("用戶名或密碼錯(cuò)誤!");
}
}
/**
* 登錄方法
*/
public boolean login(String username ,String password){
if(username == null || password == null){
return false;
}
//連接數(shù)據(jù)庫判斷是否登錄成功
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+"' ";
System.out.println(sql);
//3.獲取執(zhí)行sql的對(duì)象
stmt = conn.createStatement();
//4.執(zhí)行查詢
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實(shí)現(xiàn)
*/
public boolean login2(String username ,String password){
if(username == null || password == null){
return false;
}
//連接數(shù)據(jù)庫判斷是否登錄成功
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
//1.獲取連接
try {
conn = JDBCUtils.getConnection();
//2.定義sql
String sql = "select * from user where username = ? and password = ?";
//3.獲取執(zhí)行sql的對(duì)象
pstmt = conn.prepareStatement(sql);
//給?賦值
pstmt.setString(1,username);
pstmt.setString(2,password);
//4.執(zhí)行查詢,不需要傳遞sql
rs = pstmt.executeQuery();
//5.判斷
/* if(rs.next()){//如果有下一行,則返回true
return true;
}else{
return false;
}*/
return rs.next();//如果有下一行奔滑,則返回true
} catch (SQLException e) {
e.printStackTrace();
}finally {
JDBCUtils.close(rs,pstmt,conn);
}
return false;
}
}
JDBC控制事務(wù):
1.事務(wù):一個(gè)包含多個(gè)步驟的業(yè)務(wù)操作。如果這個(gè)業(yè)務(wù)操作被事務(wù)管理顺少,則這多個(gè)步驟要么同時(shí)成功朋其,要么同時(shí)失敗。
2.操作:
3.開啟事務(wù)
4.提交事務(wù)
5.回滾事務(wù)
6.使用Connection對(duì)象來管理事務(wù)
- 開啟事務(wù):setAutoCommit(boolean autoCommit) :調(diào)用該方法設(shè)置參數(shù)為false脆炎,即開啟事務(wù)
- 在執(zhí)行sql之前開啟事務(wù)
- 提交事務(wù):commit()
- 當(dāng)所有sql都執(zhí)行完提交事務(wù)
- 回滾事務(wù):rollback()
- 在catch中回滾事務(wù)
package com.neusoft.jdbc1;
import com.neusoft.utils.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* 事務(wù)操作
*/
public class JDBCDemo10 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
try {
//1.獲取連接
conn = JDBCUtils.getConnection();
//開啟事務(wù)
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.獲取執(zhí)行sql對(duì)象
pstmt1 = conn.prepareStatement(sql1);
pstmt2 = conn.prepareStatement(sql2);
//4. 設(shè)置參數(shù)
pstmt1.setDouble(1,500);
pstmt1.setInt(2,1);
pstmt2.setDouble(1,500);
pstmt2.setInt(2,3);
//5.執(zhí)行sql
pstmt1.executeUpdate();
// 手動(dòng)制造異常
int i = 3/0;
pstmt2.executeUpdate();
//提交事務(wù)
conn.commit();
} catch (Exception e) {
//事務(wù)回滾
try {
if(conn != null) {
conn.rollback();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
JDBCUtils.close(pstmt1,conn);
JDBCUtils.close(pstmt2,conn);
}
}
}