package com.qzh.jdbc;
import java.sql.*;
public class jdbcDML {
public static void main(String[] args) {
//创建jdbc对象
Connection conn=null;
//Statement stmt=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
//1、注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2、获取连接
conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
conn.setAutoCommit(false);//******开启事务
//3、获取数据库操作对象
//stmt=conn.createStatement();
String sql="update t_act set balance = ? where actno = ?";
ps=conn.prepareStatement(sql);
//4、执行sql
ps.setDouble(1,10000);
ps.setInt(2,111);
int count=ps.executeUpdate();
ps.setDouble(1,10000);
ps.setInt(2,222);
count+=ps.executeUpdate();
System.out.println(count==2?"转账成功!":"转账失败!");
conn.commit();//*****提交事务
//rs=stmt.executeQuery(sql);
} catch (Exception e) {
if(conn!=null){
try {
conn.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
e.printStackTrace();
}finally{
//6、释放资源
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
JDBC之DML使用
最新推荐文章于 2022-01-14 13:57:28 发布