Statement会有一个关于sql注入的bug ,所以基本不使用
一般使用PreparedStatement
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.huawei.utils.DBUtil;
public class TestJDBC02 {
public static void testPreparedStatement() throws Exception{
/**
* 预处理sql语句 不会出现sql注入的bug
*/
Connection connection = DBUtil.getConnection();
String sql = "select * from users where username=?";
//得到sql语句的 预处理对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setObject(1, "admin1' or 1=1 or username='");
ResultSet rs = preparedStatement.executeQuery();
while(rs.next()){
System.out.println(rs.getObject(1));
}
DBUtil.close(rs,preparedStatement,connection);
}
public static void testTransaction() throws Exception{
Connection connection = DBUtil.getConnection();
//默认 事务是自动提交的
//要达到手动提交的目的 必须关闭 自动提交
connection.setAutoCommit(false);
PreparedStatement ps = null;
PreparedStatement ps1 = null;
try{
ps = connection.prepareStatement("insert into A (a) values ('lisi21')");
ps1 = connection.prepareStatement("insert into B (b) values ('lisi123')");
ps.executeUpdate();
ps1.executeUpdate();
//执行完成以后 提交到数据库
connection.commit();
}catch (Exception e) {
//如果产生任何的错误 则回滚
connection.rollback();
e.printStackTrace();
}
DBUtil.close(ps,ps1,connection);
}
public static void main(String[] args) throws Exception {
testTransaction();
}
}