1. Review of commonly used methods in the Connection class
1.1 Statement createStatement() throws SQLException;
Create a Statement instance (ie: create a SQL execution object)
1.2 PreparedStatement prepareStatement(String sql) throws SQLException ;
Create a PreparedStatement object (ie: create a precompiled SQL execution object)
1.3 void setAutoCommit(boolean autoCommit) throws SQLException;
Set the automatic submission of the transaction (false means to turn off automatic submission, true to start automatic submission)
1.4 void commit() throws SQLException;
Manually commit transaction
1.5 void rollback() throws SQLException;
Manual rollback of transaction
2 Classic case where transaction rollback is required: Bank transfer case
Transfer out and transfer in are one transaction. If the transfer out is successful but the transfer in fails, the transaction needs to be rolled back. Otherwise, the balance of the transferor will decrease but the balance of the transferor will not increase.
Note: Submission of the transaction Rollback is called through the method provided by Connection; essentially the transaction still relies on the implementation of the database; The method of Connection essentially calls the database transaction mechanism.
2.1 Not using transaction control Transfer business
Disadvantages: If the transfer is successful, but the transfer fails, the balance of the transferor will be reduced, but the balance of the transferor will remain unchanged
Project structure chart
1 package cn.xiangxu.entity; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.util.Scanner; 6 7 import cn.xiangxu.tools.DBUtil; 8 9 public class Test {10 public static void main(String[] args) {11 Scanner scanner = new Scanner(System.in);12 System.out.println("请输入转出用户名:");13 String outName = scanner.nextLine();14 System.out.println("请输入需要转出的资金额度:");15 Double money = Double.parseDouble(scanner.nextLine());16 System.out.println("请输入转入用户名:");17 String inName = scanner.nextLine();18 System.out.println("转出账户为:" + outName + "转出金额为:" + money + "转入账户为:" + inName);19 20 21 Connection conn = null;22 try {23 conn = DBUtil.getConnection(); // 实例化连接对象24 25 // conn.setAutoCommit(false); // 关闭自动提交事务功能26 27 String sql = "UPDATE client "28 + "SET account = account - ? " 29 + "WHERE name = ? ";30 PreparedStatement ps = conn.prepareStatement(sql);31 ps.setDouble(1, money);32 ps.setString(2, outName);33 Integer rs = ps.executeUpdate();34 if(rs > 0) {35 System.out.println("转出成功");36 } else {37 System.out.println("转出失败");38 return; // 转出失败跳出函数,不再执行下面的语句;但是finally中的语句还是会执行的,因为就算天塌下来finally中的语句都会执行39 }40 41 System.out.println("======分割线=======");42 43 String sql_in = "UPDATE client "44 + "SET account = account + ? " 45 + "WHERE name = ? ";46 PreparedStatement ps_in = conn.prepareStatement(sql_in);47 ps_in.setDouble(1, money);48 ps_in.setString(2, inName);49 Integer judge_in = ps_in.executeUpdate();50 if(judge_in > 0) {51 System.out.println("转入成功");52 // conn.commit(); // 转出、转入都成功就提交事务53 } else {54 System.out.println("转入失败");55 // conn.rollback(); // 转出成功、转入失败就回滚事务56 }57 58 // conn.setAutoCommit(true); // 打开自动提交事务59 60 } catch (Exception e) {61 // TODO Auto-generated catch block62 e.printStackTrace();63 } finally {64 System.out.println("我是finally中的语句哟");65 try {66 DBUtil.closeConnection();67 } catch (Exception e) {68 // TODO Auto-generated catch block69 e.printStackTrace();70 }71 }72 }73 }
1 CREATE TABLE client (2 id INT (10) PRIMARY KEY,3 name VARCHAR (10),4 pwd VARCHAR (10),5 account INT (20)6 );
1 package cn.xiangxu.tools; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.sql.Connection; 6 import java.sql.SQLException; 7 import java.util.Properties; 8 9 import org.apache.commons.dbcp.BasicDataSource;10 11 public class DBUtil {12 /*13 * ThreadLocal用于线程跨方法共享数据使用14 * ThreadLocal内部有一个Map, key为需要共享数据的线程本身,value就是其需要共享的数据15 */16 private static ThreadLocal<connection> tl; // 声明一个类似于仓库的东西17 private static BasicDataSource dataSource; // 声明一个数据库连接池对象18 19 // 静态代码块,在类加载的时候执行,而且只执行一次20 static {21 tl = new ThreadLocal<connection>(); // 实例化仓库对象22 dataSource = new BasicDataSource(); // 实例数据库连接池对象23 24 Properties prop = new Properties(); // 创建一个Properties对象用(该对象可以用来加载配置文件中的属性列表)25 InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("config/mysql.properties"); // 读取配置文件信息26 try {27 prop.load(is); // 加载配置文件中的属性列表28 29 String driverClassName = prop.getProperty("driverClassName"); // 获取属性信息30 String url = prop.getProperty("url");31 String username = prop.getProperty("username");32 String password = prop.getProperty("password");33 Integer maxActive = Integer.parseInt(prop.getProperty("maxActive"));34 Integer maxWait = Integer.parseInt(prop.getProperty("maxWait"));35 36 dataSource.setDriverClassName(driverClassName); // 初始化数据库连接池(即:配置数据库连接池的先关参数)37 dataSource.setUrl(url);38 dataSource.setUsername(username);39 dataSource.setPassword(password);40 dataSource.setMaxActive(maxActive);41 dataSource.setMaxWait(maxWait);42 43 is.close(); // 关闭输入流,释放资源44 } catch (IOException e) {45 // TODO Auto-generated catch block46 e.printStackTrace();47 } 48 49 }50 51 /**52 * 创建连接对象(注意:静态方法可以直接通过类名来调用)53 * @return 连接对象54 * @throws Exception55 */56 public static Connection getConnection() throws Exception { 57 try {58 Connection conn = dataSource.getConnection(); // 创建连接对象(利用数据库连接池进行创建)59 tl.set(conn); // 将连接对象放到仓库中60 return conn; 61 } catch (Exception e) {62 // TODO Auto-generated catch block63 e.printStackTrace();64 throw e;65 }66 }67 68 /**69 * 关闭连接对象(注意:静态方法可以通过类名直接调用)70 * @throws Exception71 */72 public static void closeConnection() throws Exception {73 Connection conn = tl.get(); // 从仓库中取出连接对象74 tl.remove(); // 清空仓库75 if(conn != null) { // 判断连接对象是否释放资源76 try {77 conn.close();78 } catch (Exception e) {79 // TODO Auto-generated catch block80 e.printStackTrace();81 throw e;82 }83 }84 }85 86 }</connection></connection>
1 # zhe shi zhu shi , yi ban bu yong zhong wen 2 # deng hao liang bian mei you kong ge, mo wei mei you fen hao3 # hou mian bu neng you kong ge4 driverClassName=com.mysql.jdbc.Driver5 url=jdbc:mysql://localhost:3306/test6 username=root7 password=1828388 maxActive=1009 maxWait=3000
1 <project> 2 <modelversion>4.0.0</modelversion> 3 <groupid>cn.xiangxu</groupid> 4 <artifactid>testJDBC</artifactid> 5 <version>0.0.1-SNAPSHOT</version> 6 <dependencies> 7 <dependency> 8 <groupid>mysql</groupid> 9 <artifactid>mysql-connector-java</artifactid>10 <version>5.1.37</version>11 </dependency>12 <dependency>13 <groupid>junit</groupid>14 <artifactid>junit</artifactid>15 <version>4.12</version>16 </dependency>17 <dependency>18 <groupid>commons-dbcp</groupid>19 <artifactid>commons-dbcp</artifactid>20 <version>1.4</version>21 </dependency>22 </dependencies>23 </project>
2.2 Transfer business using transaction control
1 package cn.xiangxu.entity; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.SQLException; 6 import java.util.Scanner; 7 8 import cn.xiangxu.tools.DBUtil; 9 10 public class Test {11 public static void main(String[] args) {12 Scanner scanner = new Scanner(System.in);13 System.out.println("请输入转出用户名:");14 String outName = scanner.nextLine();15 System.out.println("请输入需要转出的资金额度:");16 Double money = Double.parseDouble(scanner.nextLine());17 System.out.println("请输入转入用户名:");18 String inName = scanner.nextLine();19 System.out.println("转出账户为:" + outName + "转出金额为:" + money + "转入账户为:" + inName);20 21 22 Connection conn = null;23 try {24 conn = DBUtil.getConnection(); // 实例化连接对象25 26 conn.setAutoCommit(false); // 关闭自动提交事务功能27 28 String sql = "UPDATE client "29 + "SET account = account - ? " 30 + "WHERE name = ? ";31 PreparedStatement ps = conn.prepareStatement(sql);32 ps.setDouble(1, money);33 ps.setString(2, outName);34 Integer rs = ps.executeUpdate();35 if(rs > 0) {36 System.out.println("转出成功");37 } else {38 System.out.println("转出失败");39 return; // 转出失败跳出函数,不再执行下面的语句;但是finally中的语句还是会执行的,因为就算天塌下来finally中的语句都会执行40 }41 42 System.out.println("======分割线=======");43 44 String sql_in = "UPDATE client "45 + "SET account = account + ? " 46 + "WHERE name = ? ";47 PreparedStatement ps_in = conn.prepareStatement(sql_in);48 ps_in.setDouble(1, money);49 ps_in.setString(2, inName);50 Integer judge_in = ps_in.executeUpdate();51 if(judge_in > 0) {52 System.out.println("转入成功");53 conn.commit(); // 转出、转入都成功就提交事务54 } else {55 System.out.println("转入失败");56 conn.rollback(); // 转出成功、转入失败就回滚事务57 }58 59 conn.setAutoCommit(true); // 打开自动提交事务60 61 } catch (Exception e) {62 // TODO Auto-generated catch block63 try {64 conn.rollback(); // 捕获到异常后也需要进行事务回滚65 } catch (SQLException e1) {66 // TODO Auto-generated catch block67 e1.printStackTrace();68 } 69 e.printStackTrace();70 } finally {71 System.out.println("我是finally中的语句哟");72 try {73 DBUtil.closeConnection();74 } catch (Exception e) {75 // TODO Auto-generated catch block76 e.printStackTrace();77 }78 }79 }80 }
2.3 Encapsulate the automatic submission function, manual submission function, and manual rollback function into In one class
1 package cn.xiangxu.tools; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.sql.Connection; 6 import java.sql.SQLException; 7 import java.util.Properties; 8 9 import org.apache.commons.dbcp.BasicDataSource; 10 11 public class DBUtil { 12 /* 13 * ThreadLocal用于线程跨方法共享数据使用 14 * ThreadLocal内部有一个Map, key为需要共享数据的线程本身,value就是其需要共享的数据 15 */ 16 private static ThreadLocal<connection> tl; // 声明一个类似于仓库的东西 17 private static BasicDataSource dataSource; // 声明一个数据库连接池对象 18 19 // 静态代码块,在类加载的时候执行,而且只执行一次 20 static { 21 tl = new ThreadLocal<connection>(); // 实例化仓库对象 22 dataSource = new BasicDataSource(); // 实例数据库连接池对象 23 24 Properties prop = new Properties(); // 创建一个Properties对象用(该对象可以用来加载配置文件中的属性列表) 25 InputStream is = DBUtil.class.getClassLoader().getResourceAsStream("config/mysql.properties"); // 读取配置文件信息 26 try { 27 prop.load(is); // 加载配置文件中的属性列表 28 29 String driverClassName = prop.getProperty("driverClassName"); // 获取属性信息 30 String url = prop.getProperty("url"); 31 String username = prop.getProperty("username"); 32 String password = prop.getProperty("password"); 33 Integer maxActive = Integer.parseInt(prop.getProperty("maxActive")); 34 Integer maxWait = Integer.parseInt(prop.getProperty("maxWait")); 35 36 dataSource.setDriverClassName(driverClassName); // 初始化数据库连接池(即:配置数据库连接池的先关参数) 37 dataSource.setUrl(url); 38 dataSource.setUsername(username); 39 dataSource.setPassword(password); 40 dataSource.setMaxActive(maxActive); 41 dataSource.setMaxWait(maxWait); 42 43 is.close(); // 关闭输入流,释放资源 44 } catch (IOException e) { 45 // TODO Auto-generated catch block 46 e.printStackTrace(); 47 } 48 49 } 50 51 /** 52 * 创建连接对象(注意:静态方法可以直接通过类名来调用) 53 * @return 连接对象 54 * @throws Exception 55 */ 56 public static Connection getConnection() throws Exception { 57 try { 58 Connection conn = dataSource.getConnection(); // 创建连接对象(利用数据库连接池进行创建) 59 tl.set(conn); // 将连接对象放到仓库中 60 return conn; 61 } catch (Exception e) { 62 // TODO Auto-generated catch block 63 e.printStackTrace(); 64 throw e; 65 } 66 } 67 68 /** 69 * 关闭连接对象(注意:静态方法可以通过类名直接调用) 70 * @throws Exception 71 */ 72 public static void closeConnection() throws Exception { 73 Connection conn = tl.get(); // 从仓库中取出连接对象 74 tl.remove(); // 清空仓库 75 if(conn != null) { // 判断连接对象是否释放资源 76 try { 77 conn.close(); 78 } catch (Exception e) { 79 // TODO Auto-generated catch block 80 e.printStackTrace(); 81 throw e; 82 } 83 } 84 } 85 86 /** 87 * 在执行SQL语句前关闭JDBC的自动提交事务功能 88 * @throws SQLException 89 */ 90 public static void tansBegin() throws SQLException { 91 try { 92 tl.get().setAutoCommit(false); // 从仓库中获取连接对象并调用setAutoCommit来关闭自动提交事务功能 93 } catch(SQLException e) { 94 e.printStackTrace(); 95 throw e; 96 } 97 } 98 99 /**100 * 手动回滚功能101 * @throws SQLException102 */103 public static void transBack() throws SQLException {104 tl.get().rollback(); // 从仓库中获取连接对象并调用rollback来实现事务回滚操作105 tl.get().setAutoCommit(true); // 回滚启动事务自动提交功能106 }107 108 /**109 * 手动提交功能110 * @throws SQLException111 */112 public static void transCommit() throws SQLException {113 tl.get().commit(); // 从仓库中获取连接对象并调用commit来实现事务提交操作114 tl.get().setAutoCommit(true); // 提交后启动事务自动提交功能115 }116 117 }</connection></connection>
1 package cn.xiangxu.entity; 2 3 import java.sql.Connection; 4 import java.sql.PreparedStatement; 5 import java.sql.SQLException; 6 import java.util.Scanner; 7 8 import cn.xiangxu.tools.DBUtil; 9 10 public class Test {11 public static void main(String[] args) {12 Scanner scanner = new Scanner(System.in);13 System.out.println("请输入转出用户名:");14 String outName = scanner.nextLine();15 System.out.println("请输入需要转出的资金额度:");16 Double money = Double.parseDouble(scanner.nextLine());17 System.out.println("请输入转入用户名:");18 String inName = scanner.nextLine();19 System.out.println("转出账户为:" + outName + "转出金额为:" + money + "转入账户为:" + inName);20 21 22 Connection conn = null;23 try {24 conn = DBUtil.getConnection(); // 实例化连接对象25 26 DBUtil.tansBegin(); // 关闭自动提交事务功能27 28 String sql = "UPDATE client "29 + "SET account = account - ? " 30 + "WHERE name = ? ";31 PreparedStatement ps = conn.prepareStatement(sql);32 ps.setDouble(1, money);33 ps.setString(2, outName);34 Integer rs = ps.executeUpdate();35 if(rs > 0) {36 System.out.println("转出成功");37 } else {38 System.out.println("转出失败");39 return; // 转出失败跳出函数,不再执行下面的语句;但是finally中的语句还是会执行的,因为就算天塌下来finally中的语句都会执行40 }41 42 System.out.println("======分割线=======");43 44 String sql_in = "UPDATE client "45 + "SET account = account + ? " 46 + "WHERE name = ? ";47 PreparedStatement ps_in = conn.prepareStatement(sql_in);48 ps_in.setDouble(1, money);49 ps_in.setString(2, inName);50 Integer judge_in = ps_in.executeUpdate();51 if(judge_in > 0) {52 System.out.println("转入成功");53 DBUtil.transCommit(); // 转出、转入都成功就提交事务54 } else {55 System.out.println("转入失败");56 DBUtil.transBack(); // 转出成功、转入失败就回滚事务57 }58 59 } catch (Exception e) {60 // TODO Auto-generated catch block61 try {62 DBUtil.transBack();// 捕获到异常后也需要进行事务回滚63 } catch (SQLException e1) {64 // TODO Auto-generated catch block65 e1.printStackTrace();66 } 67 e.printStackTrace();68 } finally {69 System.out.println("我是finally中的语句哟");70 try {71 DBUtil.closeConnection();72 } catch (Exception e) {73 // TODO Auto-generated catch block74 e.printStackTrace();75 }76 }77 }78 }
The above is the detailed content of JDBC implementation of transaction submission and rollback examples. For more information, please follow other related articles on the PHP Chinese website!

Java8-291之后,禁用了TLS1.1,使JDBC无法用SSL连接SqlServer2008怎么办,以下是解决办法修改java.security文件1.找到jre的java.security文件如果是jre,在{JAVA_HOME}/jre/lib/security中,比如????C:\ProgramFiles\Java\jre1.8.0_301\lib\security如果是Eclipse绿色免安装便携版在安装文件夹搜索java.security,比如????xxx\plugins\org

Lockwaittimeoutexceeded;tryrestartingtransaction-如何解决MySQL报错:事务等待超时在使用MySQL数据库时,有时可能会遇到一个常见的错误:Lockwaittimeoutexceeded;tryrestartingtransaction,该错误表示事务等待超时。这个错误通常发生在并

近年来,Java语言的应用越来越广泛,而JDBCAPI是Java应用程序中与数据库交互的一种创造性方法,JDBC基于一种名为ODBC的开放数据库连接标准,使得Java应用程序能够连入任何数据库管理系统(DBMS)。其中,MySQL更是一款备受青睐的数据库管理系统。然而,连接MySQL数据库时,开发人员也会遇到一些常见问题,本文旨在介绍JDBCAPI连接M

随着Java的广泛应用,Java程序在连接数据库时经常会出现JDBC错误。JDBC(JavaDatabaseConnectivity)是Java中用于连接数据库的编程接口,因此,JDBC错误是在Java程序与数据库交互时遇到的一种错误。下面将介绍一些最常见的JDBC错误及如何解决和避免它们。ClassNotFoundException这是最常见的JDBC

一、说明在JDBC中,executeBatch这个方法可以将多条dml语句批量执行,效率比单条执行executeUpdate高很多,这是什么原理呢?在mysql和oracle中又是如何实现批量执行的呢?本文将给大家介绍这背后的原理。二、实验介绍本实验将通过以下三步进行a.记录jdbc在mysql中批量执行和单条执行的耗时b.记录jdbc在oracle中批量执行和单条执行的耗时c.记录oracleplsql批量执行和单条执行的耗时相关java和数据库版本如下:Java17,Mysql8,Oracl

一、数据库编程的必备条件编程语言,如Java,C、C++、Python等数据库,如Oracle,MySQL,SQLServer等数据库驱动包:不同的数据库,对应不同的编程语言提供了不同的数据库驱动包,如:MySQL提供了Java的驱动包mysql-connector-java,需要基于Java操作MySQL即需要该驱动包。同样的,要基于Java操作Oracle数据库则需要Oracle的数据库驱动包ojdbc。二、Java的数据库编程:JDBCJDBC,即JavaDatabaseConnectiv

1.PDO简介PDO是PHP的一个扩展库,它提供了一个面向对象的方式来操作数据库。PDO支持多种数据库,包括Mysql、postgresql、oracle、SQLServer等。PDO使开发人员能够使用统一的api来操作不同的数据库,这使得开发人员可以在不同的数据库之间轻松切换。2.PDO连接数据库要使用PDO连接数据库,首先需要创建一个PDO对象。PDO对象的构造函数接收三个参数:数据库类型、主机名、数据库用户名和密码。例如,以下代码创建了一个连接到mysql数据库的对象:$dsn="mysq

PHP数据对象(PDO)扩展提供了与数据库服务器高效且面向对象的交互。其高级查询和更新功能使开发人员能够执行复杂的数据库操作,从而提高性能和代码可维护性。本文将深入探讨PDO的高级查询和更新功能,指导您掌握其强大功能。高级查询:使用占位符和绑定参数占位符和绑定参数是提高查询性能和安全性的重要工具。占位符使用问号(?)表示查询中可替换的参数,而绑定参数则允许指定每个参数的数据类型和值。通过使用这些方法,您可以避免sql注入攻击并提高性能,因为数据库引擎可以提前优化查询。//使用占位符$stmt=$


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),