-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTransferAccountTransaction.java
More file actions
88 lines (71 loc) · 2.32 KB
/
TransferAccountTransaction.java
File metadata and controls
88 lines (71 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package transaction;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
public class TransferAccountTransaction {
private static String driver="com.mysql.jdbc.Driver";
private static String user="root";
private static String password="cpprootmysql";
private static String url="jdbc:mysql://localhost:3306/test";
static Connection connection=null;
PreparedStatement preparedStatement=null;
public static Connection getConnection() throws SQLException, ClassNotFoundException{
Class.forName(driver);
return (Connection)DriverManager.getConnection(url, user, password);
}
public static User getUser(String name){
try {
String sql="select * from user where name=?";
connection=getConnection();
connection.setAutoCommit(false);
PreparedStatement pre= (PreparedStatement) connection.prepareStatement(sql);
pre.setString(1, name);
ResultSet resultSet= pre.executeQuery();
User user=new User(resultSet.getInt("id"),resultSet.getString("name"),resultSet.getString("password"),resultSet.getDouble("money"),resultSet.getInt("flag"));
return user;
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
try {
connection.rollback();
return null;
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}finally {
try {
connection.setAutoCommit(true);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
public void transfer(int fromId,int toId,double money){
try {
User from=getUser("zhou");
User to=getUser("chen");
String sql="update user set money=? where id=?";
connection=getConnection();
connection.setAutoCommit(false);
//转钱操作
preparedStatement=(PreparedStatement) connection.prepareCall(sql);
preparedStatement.setDouble(1, money);
preparedStatement.setInt(2, fromId);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
}
}