1.JDBC访问数据库工具类
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* 事务操作
*/
public class JdbcDemo10 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt1 = null;
PreparedStatement pstmt2 = null;
//1.获取连接
try {
conn = JdbcUtils.getConnetion();
//开启事务
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.获取执行sql对象
pstmt1 = conn.prepareStatement(sql1);
pstmt2 = conn.prepareStatement(sql2);
//4.设置参数
pstmt1.setDouble(1,500);
pstmt1.setInt(2,1);
pstmt2.setDouble(1,500);
pstmt2.setInt(2,2);
//5.执行sql
pstmt1.executeUpdate();
//int i=3/0; //制作错误为了测试“事务管理”功能
pstmt2.executeUpdate();
conn.commit();
} catch (Exception e) {
//事务的回滚
try {
if(null != conn) {
conn.rollback();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
e.printStackTrace();
}finally {
JdbcUtils.close(pstmt1,pstmt2,conn);
}
}
}
2.PrepareStatem程序部分
/**
* 登入方法,使用PreparedStatement实现
* 防止sql渗透攻击
*/
public boolean login2(String username,String password){
if(null == username && null == password){
return false;
}
Connection conn =null;
PreparedStatement pstmt =null;
ResultSet res=null;
//连接数据库判断是否登录成功
//1.获取数据库连接
try {
conn = JdbcUtils.getConnetion();
//2.定义sql
String sql = "select * from login where username= ? and password= ?";
//3.获取执行sql的对象
pstmt = conn.prepareStatement(sql);
//给问号赋值
pstmt.setString(1,username);//第一个问号
pstmt.setString(2,password);//第二个问号
//4.执行sql时,不需要传递sql
res = pstmt.executeQuery();
//5.判断
/*if(res.next()){//如果有下一行,则返回true
return true;
}else{
return false;
}*/
return res.next();
} catch (SQLException e) {
e.printStackTrace();
}finally{
JdbcUtils.close(res,pstmt,conn);
}
return false;
}