MySQL_(Java)使用JDBC向数据库发起查询请求  传送门

  MySQL_(Java)使用JDBC向数据库中插入(insert)数据  传送门

  MySQL_(Java)使用JDBC向数据库中删除(delete)数据  传送门

  MySQL_(Java)使用JDBC向数据库中修改(update)数据  传送门

  MySQL_(Java)【连接池】简单在JDBCUtils.java中创建连接池  传送门

数据库中事务:

  我们之前分享数据库的数据操作,无外乎对数据库的数据进行增、删、改、查。就比如我们去买东西,一般都是先付钱,卖家收到钱再发货。这个用数据库来表示就是,第一步:从用户的账户中减去一部分金额。第二步,再把减去的金额添加到商家的账户上。

  但是万一遇到特殊的情况,你成功的完成了第一步,从用户的数据库中扣除了钱,这时候突然停电,系统出现了故障,没有完成第二步。这就尴尬了,用户的钱少了,商家也没收到钱。

  为了应对这种情况的发生,数据库就出现了一个功能事务,事务就是一组由 SQL 语句组成的业务逻辑,当事务内的所有 SQL语句都成功的执行,整个事务才算成功,否则就是失败。失败意味着整个的数据操作没有意义,就要把数据恢复到执行事务操作之前的状态。

  Learn

    一、未添加事务且普通转账正常 

    二、在扣款和收款操作之间添加一个隐式异常

    三、添加事物

数据库表结构:

    

一、未添加事务且普通转账正常   

  由a向b转账1000元

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class JDBC01 { public static void main(String[] args) throws SQLException {
transferAccount("a","b",1000);
} public static void selectAll() throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
//数据库的连接
con = JDBCUtils.getConnection(); //数据库的增删改查
stmt = con.createStatement();
//返回一个结果集
rs =stmt.executeQuery("select * from garytb"); while(rs.next()) {
//System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3));
System.out.println(rs.getString("id")+","+rs.getString("username")+","+rs.getString("password"));
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JDBCUtils.close(rs, stmt, con);
}
} //校验用户
public static boolean selectByUernamePassword(String username,String password) throws SQLException {
Connection con=null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver"); String url ="jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
con = DriverManager.getConnection(url,"root","123456");
stmt =con.createStatement();
String sql = "select * from garytb where username = '"+username+"' and password = '"+password+"'";
//System.out.println(sql);
rs = stmt.executeQuery(sql); if(rs.next()) {
return true;
}else {
return false;
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
} return false;
} public static boolean selectByUP2(String username,String password) throws SQLException{
Connection con=null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver"); String url ="jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
con = DriverManager.getConnection(url,"root","123456"); String sql = "select * from garytb where username = ? and password = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
//添加参数
pstmt.setString(1, username);
pstmt.setString(2, password);
//进行查询
rs = pstmt.executeQuery(); if(rs.next()) {
return true;
}else {
return false;
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
} return false;
} //pageNumber是页数,第几页,pageCount是每页显示多少个数据
public static void selectUserByPage(int pageNumber,int pageCount) throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver"); //String url ="jdbc:mysql://localhost:3306/garysql";
//指定编码查询数据库
String url ="jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
String user = "root";
String password = "123456";
//建立和数据库的连接
con = DriverManager.getConnection(url,user,password); stmt = con.prepareStatement("select * from garytb limit ?,?");
stmt.setInt(1, (pageNumber-1)*pageCount );
stmt.setInt(2, pageCount); rs = stmt.executeQuery(); while(rs.next()) {
//System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3));
System.out.println(rs.getString("id")+","+rs.getString("username")+","+rs.getString("password"));
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
}
} //crud: create read update delete
//插入语句
public static void insert(String username,String password) throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection();
String sql = "insert into garytb(username,password) values(?,?)";
stmt = con.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
int result =stmt.executeUpdate();// 返回值代表收到影响的行数
System.out.println("插入成功"+username);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JDBCUtils.close(rs, stmt, con);
}
}
//删除语句
public static void delete(int id) throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection(); String sql = "delete from garytb where id = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, id);
int result =stmt.executeUpdate();// 返回值代表收到影响的行数
if(result>0) {
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stmt, con);
}
}
//修改语句
public static void update(int id,String newPassword) throws SQLException {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection(); String sql = "update garytb set password = ? where id = ?";
stmt = con.prepareStatement(sql);
stmt.setString(1, newPassword);
stmt.setInt(2, id);
int result =stmt.executeUpdate();// 返回值代表收到影响的行数
if(result>0) {
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stmt, con);
}
} //事物操作
//由username1向username2转账金额
public static void transferAccount(String username1,String username2,int money) throws SQLException {
Connection con = null;
PreparedStatement stmt1 = null;
PreparedStatement stmt2 = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection(); String sql = "update garytb set balance = balance - ? where username = ?";
stmt1 = con.prepareStatement(sql);
stmt1.setInt(1, money);
stmt1.setString(2, username1);
stmt1.executeUpdate();// 返回值代表收到影响的行数 sql = "update garytb set balance = balance + ? where username = ?";
stmt2 = con.prepareStatement(sql);
stmt2.setInt(1, money);
stmt2.setString(2, username2);
stmt2.executeUpdate();// 返回值代表收到影响的行数
System.out.println("操作成功!!");
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stmt1, con);
}
} }

JDBC01.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class JDBCUtils { private static final String connectionURL = "jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
private static final String username = "root";
private static final String password = "123"; //创建数据库的连接
public static Connection getConnection() {
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(connectionURL,username,password);
} catch (Exception e) { e.printStackTrace();
}
return null;
} //关闭数据库的连接
public static void close(ResultSet rs,Statement stmt,Connection con) throws SQLException {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
}
}

JDBCUtils.java

  转账资源操作【资源关闭】优化版

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class JDBC01 { public static void main(String[] args) throws SQLException {
transferAccount("a","b",1000);
} public static void selectAll() throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
//数据库的连接
con = JDBCUtils.getConnection(); //数据库的增删改查
stmt = con.createStatement();
//返回一个结果集
rs =stmt.executeQuery("select * from garytb"); while(rs.next()) {
//System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3));
System.out.println(rs.getString("id")+","+rs.getString("username")+","+rs.getString("password"));
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JDBCUtils.close(rs, stmt, con);
}
} //校验用户
public static boolean selectByUernamePassword(String username,String password) throws SQLException {
Connection con=null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver"); String url ="jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
con = DriverManager.getConnection(url,"root","123456");
stmt =con.createStatement();
String sql = "select * from garytb where username = '"+username+"' and password = '"+password+"'";
//System.out.println(sql);
rs = stmt.executeQuery(sql); if(rs.next()) {
return true;
}else {
return false;
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
} return false;
} public static boolean selectByUP2(String username,String password) throws SQLException{
Connection con=null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver"); String url ="jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
con = DriverManager.getConnection(url,"root","123456"); String sql = "select * from garytb where username = ? and password = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
//添加参数
pstmt.setString(1, username);
pstmt.setString(2, password);
//进行查询
rs = pstmt.executeQuery(); if(rs.next()) {
return true;
}else {
return false;
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
} return false;
} //pageNumber是页数,第几页,pageCount是每页显示多少个数据
public static void selectUserByPage(int pageNumber,int pageCount) throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver"); //String url ="jdbc:mysql://localhost:3306/garysql";
//指定编码查询数据库
String url ="jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
String user = "root";
String password = "123456";
//建立和数据库的连接
con = DriverManager.getConnection(url,user,password); stmt = con.prepareStatement("select * from garytb limit ?,?");
stmt.setInt(1, (pageNumber-1)*pageCount );
stmt.setInt(2, pageCount); rs = stmt.executeQuery(); while(rs.next()) {
//System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3));
System.out.println(rs.getString("id")+","+rs.getString("username")+","+rs.getString("password"));
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
}
} //crud: create read update delete
//插入语句
public static void insert(String username,String password) throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection();
String sql = "insert into garytb(username,password) values(?,?)";
stmt = con.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
int result =stmt.executeUpdate();// 返回值代表收到影响的行数
System.out.println("插入成功"+username);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JDBCUtils.close(rs, stmt, con);
}
}
//删除语句
public static void delete(int id) throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection(); String sql = "delete from garytb where id = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, id);
int result =stmt.executeUpdate();// 返回值代表收到影响的行数
if(result>0) {
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stmt, con);
}
}
//修改语句
public static void update(int id,String newPassword) throws SQLException {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection(); String sql = "update garytb set password = ? where id = ?";
stmt = con.prepareStatement(sql);
stmt.setString(1, newPassword);
stmt.setInt(2, id);
int result =stmt.executeUpdate();// 返回值代表收到影响的行数
if(result>0) {
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stmt, con);
}
} //事物操作
//由username1向username2转账金额
public static void transferAccount(String username1,String username2,int money) throws SQLException {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection(); String sql = "update garytb set balance = balance - ? where username = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, money);
stmt.setString(2, username1);
stmt.executeUpdate();// 返回值代表收到影响的行数 sql = "update garytb set balance = balance + ? where username = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, money);
stmt.setString(2, username2);
stmt.executeUpdate();// 返回值代表收到影响的行数
System.out.println("操作成功!!");
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stmt, con);
}
} }

JDBC01.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList; public class JDBCUtils { private static final String connectionURL = "jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
private static final String username = "root";
private static final String password = "123"; private static ArrayList<Connection> conList = new ArrayList<Connection>(); static {
for(int i =0;i<5;i++) {
Connection con = createConnection();
conList.add(con);
}
} public static Connection getConnection() {
if(conList.isEmpty()==false) {
Connection con = conList.get(0);
conList.remove(con);
return con;
}else {
return createConnection();
}
} private static Connection createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver"); return DriverManager.getConnection(connectionURL, username, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return null;
} public static void close(ResultSet rs,Statement stmt,Connection con) {
closeResultSet(rs);
closeStatement(stmt);
closeConnection(con);
}
public static void close(Statement stmt1,Statement stmt2,Connection con) {
closeStatement(stmt1);
closeStatement(stmt2);
closeConnection(con);
} private static void closeResultSet(ResultSet rs ) {
try {
if(rs!=null)rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void closeStatement(Statement stmt) {
try {
if(stmt!=null)
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void closeConnection(Connection con) {
// try {
// if(con!=null)con.close();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
conList.add(con);
}
}

JDBCUtils.java

    //由username1向username2转账金额
public static void transferAccount(String username1,String username2,int money) throws SQLException {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection(); String sql = "update garytb set balance = balance - ? where username = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, money);
stmt.setString(2, username1);
stmt.executeUpdate();// 返回值代表收到影响的行数 sql = "update garytb set balance = balance + ? where username = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, money);
stmt.setString(2, username2);
stmt.executeUpdate();// 返回值代表收到影响的行数
System.out.println("操作成功!!");
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stmt, con);
}
}

二、在扣款和收款操作之间添加一个隐式异常

  当程序运行到异常代码块时,程序不会往下继续执行,因此a方1000元已扣除但b方未收到1000元款项

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class JDBC01 { public static void main(String[] args) throws SQLException {
transferAccount("a","b",1000);
} public static void selectAll() throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
//数据库的连接
con = JDBCUtils.getConnection(); //数据库的增删改查
stmt = con.createStatement();
//返回一个结果集
rs =stmt.executeQuery("select * from garytb"); while(rs.next()) {
//System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3));
System.out.println(rs.getString("id")+","+rs.getString("username")+","+rs.getString("password"));
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JDBCUtils.close(rs, stmt, con);
}
} //校验用户
public static boolean selectByUernamePassword(String username,String password) throws SQLException {
Connection con=null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver"); String url ="jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
con = DriverManager.getConnection(url,"root","123456");
stmt =con.createStatement();
String sql = "select * from garytb where username = '"+username+"' and password = '"+password+"'";
//System.out.println(sql);
rs = stmt.executeQuery(sql); if(rs.next()) {
return true;
}else {
return false;
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
} return false;
} public static boolean selectByUP2(String username,String password) throws SQLException{
Connection con=null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver"); String url ="jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
con = DriverManager.getConnection(url,"root","123456"); String sql = "select * from garytb where username = ? and password = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
//添加参数
pstmt.setString(1, username);
pstmt.setString(2, password);
//进行查询
rs = pstmt.executeQuery(); if(rs.next()) {
return true;
}else {
return false;
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
} return false;
} //pageNumber是页数,第几页,pageCount是每页显示多少个数据
public static void selectUserByPage(int pageNumber,int pageCount) throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver"); //String url ="jdbc:mysql://localhost:3306/garysql";
//指定编码查询数据库
String url ="jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
String user = "root";
String password = "123456";
//建立和数据库的连接
con = DriverManager.getConnection(url,user,password); stmt = con.prepareStatement("select * from garytb limit ?,?");
stmt.setInt(1, (pageNumber-1)*pageCount );
stmt.setInt(2, pageCount); rs = stmt.executeQuery(); while(rs.next()) {
//System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3));
System.out.println(rs.getString("id")+","+rs.getString("username")+","+rs.getString("password"));
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
}
} //crud: create read update delete
//插入语句
public static void insert(String username,String password) throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection();
String sql = "insert into garytb(username,password) values(?,?)";
stmt = con.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
int result =stmt.executeUpdate();// 返回值代表收到影响的行数
System.out.println("插入成功"+username);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JDBCUtils.close(rs, stmt, con);
}
}
//删除语句
public static void delete(int id) throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection(); String sql = "delete from garytb where id = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, id);
int result =stmt.executeUpdate();// 返回值代表收到影响的行数
if(result>0) {
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stmt, con);
}
}
//修改语句
public static void update(int id,String newPassword) throws SQLException {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection(); String sql = "update garytb set password = ? where id = ?";
stmt = con.prepareStatement(sql);
stmt.setString(1, newPassword);
stmt.setInt(2, id);
int result =stmt.executeUpdate();// 返回值代表收到影响的行数
if(result>0) {
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stmt, con);
}
} //事物操作
//由username1向username2转账金额
public static void transferAccount(String username1,String username2,int money) {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection(); String sql = "update garytb set balance = balance - ? where username = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, money);
stmt.setString(2, username1);
stmt.executeUpdate();// 返回值代表收到影响的行数 //显示异常throw new Exception("出现错误");
//隐示异常 空指针异常
String s = null;
s.charAt(2); sql = "update garytb set balance = balance + ? where username = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, money);
stmt.setString(2, username2);
stmt.executeUpdate();// 返回值代表收到影响的行数
System.out.println("操作成功!!");
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stmt, con);
}
} }

JDBC01.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList; public class JDBCUtils { private static final String connectionURL = "jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
private static final String username = "root";
private static final String password = "123"; private static ArrayList<Connection> conList = new ArrayList<Connection>(); static {
for(int i =0;i<5;i++) {
Connection con = createConnection();
conList.add(con);
}
} public static Connection getConnection() {
if(conList.isEmpty()==false) {
Connection con = conList.get(0);
conList.remove(con);
return con;
}else {
return createConnection();
}
} private static Connection createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver"); return DriverManager.getConnection(connectionURL, username, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return null;
} public static void close(ResultSet rs,Statement stmt,Connection con) {
closeResultSet(rs);
closeStatement(stmt);
closeConnection(con);
}
public static void close(Statement stmt1,Statement stmt2,Connection con) {
closeStatement(stmt1);
closeStatement(stmt2);
closeConnection(con);
} private static void closeResultSet(ResultSet rs ) {
try {
if(rs!=null)rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void closeStatement(Statement stmt) {
try {
if(stmt!=null)
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void closeConnection(Connection con) {
// try {
// if(con!=null)con.close();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
conList.add(con);
}
}

JDBCUtils.java

    //由username1向username2转账金额
public static void transferAccount(String username1,String username2,int money) {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection(); String sql = "update garytb set balance = balance - ? where username = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, money);
stmt.setString(2, username1);
stmt.executeUpdate();// 返回值代表收到影响的行数 //显示异常throw new Exception("出现错误");
//隐示异常 空指针异常
String s = null;
s.charAt(2); sql = "update garytb set balance = balance + ? where username = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, money);
stmt.setString(2, username2);
stmt.executeUpdate();// 返回值代表收到影响的行数
System.out.println("操作成功!!");
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stmt, con);
}
}

三、添加事物  

  一旦事物之间出现异常,则不会提交事物给数据库

  //开启事物 是否自动提交
  con.setAutoCommit(false);   //当事物中所有事物都完成了才会提交
  con.commit();

  当a向b转账1000元后出现异常,b未收到1000元,这一系列操作处于同一事物中,此事物有异常不会提交给程序

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; public class JDBC01 { public static void main(String[] args) throws SQLException {
transferAccount("a","b",1000);
} public static void selectAll() throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
//数据库的连接
con = JDBCUtils.getConnection(); //数据库的增删改查
stmt = con.createStatement();
//返回一个结果集
rs =stmt.executeQuery("select * from garytb"); while(rs.next()) {
//System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3));
System.out.println(rs.getString("id")+","+rs.getString("username")+","+rs.getString("password"));
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JDBCUtils.close(rs, stmt, con);
}
} //校验用户
public static boolean selectByUernamePassword(String username,String password) throws SQLException {
Connection con=null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver"); String url ="jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
con = DriverManager.getConnection(url,"root","123456");
stmt =con.createStatement();
String sql = "select * from garytb where username = '"+username+"' and password = '"+password+"'";
//System.out.println(sql);
rs = stmt.executeQuery(sql); if(rs.next()) {
return true;
}else {
return false;
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
} return false;
} public static boolean selectByUP2(String username,String password) throws SQLException{
Connection con=null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver"); String url ="jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
con = DriverManager.getConnection(url,"root","123456"); String sql = "select * from garytb where username = ? and password = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
//添加参数
pstmt.setString(1, username);
pstmt.setString(2, password);
//进行查询
rs = pstmt.executeQuery(); if(rs.next()) {
return true;
}else {
return false;
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
} return false;
} //pageNumber是页数,第几页,pageCount是每页显示多少个数据
public static void selectUserByPage(int pageNumber,int pageCount) throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver"); //String url ="jdbc:mysql://localhost:3306/garysql";
//指定编码查询数据库
String url ="jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
String user = "root";
String password = "123456";
//建立和数据库的连接
con = DriverManager.getConnection(url,user,password); stmt = con.prepareStatement("select * from garytb limit ?,?");
stmt.setInt(1, (pageNumber-1)*pageCount );
stmt.setInt(2, pageCount); rs = stmt.executeQuery(); while(rs.next()) {
//System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3));
System.out.println(rs.getString("id")+","+rs.getString("username")+","+rs.getString("password"));
} } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(con!=null)
con.close();
}
} //crud: create read update delete
//插入语句
public static void insert(String username,String password) throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection();
String sql = "insert into garytb(username,password) values(?,?)";
stmt = con.prepareStatement(sql);
stmt.setString(1, username);
stmt.setString(2, password);
int result =stmt.executeUpdate();// 返回值代表收到影响的行数
System.out.println("插入成功"+username);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
JDBCUtils.close(rs, stmt, con);
}
}
//删除语句
public static void delete(int id) throws SQLException {
//注册驱动 使用驱动连接数据库
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection(); String sql = "delete from garytb where id = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, id);
int result =stmt.executeUpdate();// 返回值代表收到影响的行数
if(result>0) {
System.out.println("删除成功");
}else {
System.out.println("删除失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stmt, con);
}
}
//修改语句
public static void update(int id,String newPassword) throws SQLException {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection(); String sql = "update garytb set password = ? where id = ?";
stmt = con.prepareStatement(sql);
stmt.setString(1, newPassword);
stmt.setInt(2, id);
int result =stmt.executeUpdate();// 返回值代表收到影响的行数
if(result>0) {
System.out.println("修改成功");
}else {
System.out.println("修改失败");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stmt, con);
}
} //事物操作
//由username1向username2转账金额
public static void transferAccount(String username1,String username2,int money) {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection(); //开启事物 是否自动提交
con.setAutoCommit(false); String sql = "update garytb set balance = balance - ? where username = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, money);
stmt.setString(2, username1);
stmt.executeUpdate();// 返回值代表收到影响的行数 //显示异常throw new Exception("出现错误");
//隐示异常 空指针异常 sql = "update garytb set balance = balance + ? where username = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, money);
stmt.setString(2, username2);
stmt.executeUpdate();// 返回值代表收到影响的行数
System.out.println("操作成功!!"); //提交事务
//当事物中所有事物都完成了才会提交
con.commit(); } catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stmt, con);
}
} }

JDBC01.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList; public class JDBCUtils { private static final String connectionURL = "jdbc:mysql://localhost:3306/garysql?useUnicode=true&characterEncoding=UTF8&useSSL=false";
private static final String username = "root";
private static final String password = "123"; private static ArrayList<Connection> conList = new ArrayList<Connection>(); static {
for(int i =0;i<5;i++) {
Connection con = createConnection();
conList.add(con);
}
} public static Connection getConnection() {
if(conList.isEmpty()==false) {
Connection con = conList.get(0);
conList.remove(con);
return con;
}else {
return createConnection();
}
} private static Connection createConnection() {
try {
Class.forName("com.mysql.jdbc.Driver"); return DriverManager.getConnection(connectionURL, username, password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return null;
} public static void close(ResultSet rs,Statement stmt,Connection con) {
closeResultSet(rs);
closeStatement(stmt);
closeConnection(con);
}
public static void close(Statement stmt1,Statement stmt2,Connection con) {
closeStatement(stmt1);
closeStatement(stmt2);
closeConnection(con);
} private static void closeResultSet(ResultSet rs ) {
try {
if(rs!=null)rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void closeStatement(Statement stmt) {
try {
if(stmt!=null)
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void closeConnection(Connection con) {
// try {
// if(con!=null)con.close();
// } catch (SQLException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
conList.add(con);
}
}

JDBCUtils.java

//事物操作
//由username1向username2转账金额
public static void transferAccount(String username1,String username2,int money) {
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = JDBCUtils.getConnection(); //开启事物 是否自动提交
con.setAutoCommit(false); String sql = "update garytb set balance = balance - ? where username = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, money);
stmt.setString(2, username1);
stmt.executeUpdate();// 返回值代表收到影响的行数 //显示异常throw new Exception("出现错误");
//隐示异常 空指针异常 sql = "update garytb set balance = balance + ? where username = ?";
stmt = con.prepareStatement(sql);
stmt.setInt(1, money);
stmt.setString(2, username2);
stmt.executeUpdate();// 返回值代表收到影响的行数
System.out.println("操作成功!!"); //提交事务
//当事物中所有事物都完成了才会提交
con.commit(); } catch (Exception e) {
e.printStackTrace();
} finally {
JDBCUtils.close(rs, stmt, con);
}
}

MySQL_(Java)【事物操作】使用JDBC模拟银行转账向数据库发起修改请求的更多相关文章

  1. MySQL_(Java)使用JDBC向数据库发起查询请求

    MySQL_(Java)使用JDBC向数据库发起查询请求 传送门 MySQL_(Java)使用JDBC创建用户名和密码校验查询方法 传送门 MySQL_(Java)使用preparestatement ...

  2. 编写Java程序,使用JDBC连接SQL Server数据库

    返回本章节 返回作业目录 需求说明: 使用JDBC连接SQL Server数据库 SQL Server数据库位于192.168.2.101. 所需连接的数据库为eshop_db,用户名为test,密码 ...

  3. charles 模拟手机弱网、修改请求参数、修改返回值

    1.charles模拟弱网(断网) 2.charles修改请求参数 (1)先访问一次需要改的请求,在charles上找到相应的请求地址 (2)然后在需要打断点的请求上右键,勾选[Breakpoints ...

  4. JAVA高级编程序——JDBC(连接mysql数据库)——(一)

    java要想连接数据库,就要用JDBC(java database connection),用这个jar包 (mysql-connector-java-xxx-xx-bin.jar) sun公司为我们 ...

  5. MySQL_(Java)【连接池】使用DBCP简单模拟银行转账事物

    dbcp下载 传送门 Commons Pool下载 传送门 Commons log下载 传送门 MySQL_(Java)[事物操作]使用JDBC模拟银行转账向数据库发起修改请求 传送门 MySQL_( ...

  6. MySQL_(Java)【连接池】简单在JDBCUtils.java中创建连接池

    MySQL_(Java)[事物操作]使用JDBC模拟银行转账向数据库发起修改请求 传送门 MySQL_(Java)[连接池]使用DBCP简单模拟银行转账事物 传送门 Java应用程序访问数据库的过程: ...

  7. MySQL_(Java)使用JDBC向数据库中修改(update)数据

    MySQL_(Java)使用JDBC向数据库发起查询请求 传送门 MySQL_(Java)使用JDBC向数据库中插入(insert)数据 传送门 MySQL_(Java)使用JDBC向数据库中删除(d ...

  8. MySQL_(Java)使用JDBC向数据库中删除(delete)数据

    MySQL_(Java)使用JDBC向数据库发起查询请求 传送门 MySQL_(Java)使用JDBC向数据库中插入(insert)数据 传送门 MySQL_(Java)使用JDBC向数据库中删除(d ...

  9. MySQL_(Java)使用JDBC向数据库中插入(insert)数据

    MySQL_(Java)使用JDBC向数据库发起查询请求 传送门 MySQL_(Java)使用JDBC向数据库中插入(insert)数据 传送门 MySQL_(Java)使用JDBC向数据库中删除(d ...

随机推荐

  1. 快速上手小程序的mpvue框架

    一.什么是mpvue框架? mpvue 是一个使用 Vue.js 开发小程序的前端框架.框架基于 Vue.js 核心(所以建议熟练掌握vue再使用mpvue框架,否则还是建议去使用原生框架去写小程序) ...

  2. 3.Shell的基本功能

    3.Shell的基本功能Bash是Bourne-Again Shell的缩写.Bourne Shell的内部命令在Bash中同样适用.3.1 Shell语法3.1.1 Shell操作shell读取和执 ...

  3. 【原创】大叔经验分享(65)spark读取不到hive表

    spark 2.4.3 spark读取hive表,步骤: 1)hive-site.xml hive-site.xml放到$SPARK_HOME/conf下 2)enableHiveSupport Sp ...

  4. luogu P3645 [APIO2015]雅加达的摩天楼

    luogu 暴力? 暴力! 这个题有点像最短路,所以设\(f_{i,j}\)表示在\(i\)号楼,当前\(doge\)跳跃能力为\(j\)的最短步数,转移要么跳一步到\(f_{i+j,j}\)和\(f ...

  5. Selenium 基本使用

    from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.c ...

  6. QQ大盗 - 巧用clientkey

    场景: 1.将程序发给好友,好友打开 qq昵称就会被秒改为”账号已被盗“. 2.将程序运行在自己的电脑,让那些随意借用电脑看片聊天的室友产生一个觉悟:乱使用别人电脑很可能会泄露隐私. 思路: 通过数据 ...

  7. 【转】bitbake 笔记

    原文 http://blog.csdn.net/xiaofeng_yan/article/details/6757725 1 当你已经编完一个系统比如sato映像,在编一个meta-toolchain ...

  8. STM32WB AHB总线、APB总线与外设

    方框图: 如图所示: 1)APB1外设 2)APB2外设 3)AHB1外设 4)AHB2外设 5)AHB3外设 6)AHB4外设(ABH共享总线外设) 内存映射关系图:

  9. python函数:匿名函数、函数递归与二分法、面向过程编程

    今天主要讲三大部分内容: 一.匿名函数二.函数递归与二分法三.面向过程编程 一.匿名函数: """ 1. 什么时匿名函数 def定义的是有名函数:特点是可以通过名字重复调 ...

  10. Kaggle_泰坦尼克乘客存活预测

    转载 逻辑回归应用之Kaggle泰坦尼克之灾 此转载只为保存!!! ————————————————版权声明:本文为CSDN博主「寒小阳」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附 ...