一:事物操作
public static void Transaction() throws SQLException {
String sql1="update team set name='VVVV' where id=1";
String sql2="update team set name='HH啊哈哈' where id=2";
PreparedStatement stmt=null;
Savepoint point=null;
Connection con=SqlHelper.getConnection();
try{
con.setAutoCommit(false); //设置手动事物
/**
* 第一次执行sql
* */
stmt=con.prepareStatement(sql1);
stmt.executeUpdate();
//设置事物回滚的点
point= con.setSavepoint();
//第二次执行sql
stmt=con.prepareStatement(sql2);
stmt.executeUpdate();
}
catch(Exception ex){
//回滚到设置的回滚的位置
con.rollback(point);
}
finally{
//提交事物
con.commit();
SqlHelper.Distory(con, stmt);
System.out.println("ok!");
}
System.out.println("执行完毕~~~~~~~~~");
}
事物是通过Connection类操作的 默认是的con.setAutoCommit(true) 自动提交事物,在操作事务的时候可以设置回滚的点 根据自己的需求回滚
二:批处理操作 为了减少对数据库的操作 提升性能 批量操作是数据库不可缺少的 具体例子如下 ```
public static void AddManyDate() throws SQLException{
String sql="INSERT INTO team(name,slogan,leader) values(?,?,?)";
PreparedStatement stmt=null;
Connection conn=null;
try {
conn=SqlHelper.getConnection();
stmt=conn.prepareStatement(sql);
//模拟批处理
for(int i=0;i<10;i++){
stmt.setString(1,"aaa"+i);
stmt.setString(2, "bbb"+i);
stmt.setString(3, "ccc"+i);
//加入批处理
stmt.addBatch();
//创建一个执行策略
if(i%5==0){
//执行批量操作
stmt.executeBatch();
stmt.clearBatch();
}
}
stmt.executeBatch();
stmt.clearBatch();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
SqlHelper.Distory(conn, stmt);
}
System.out.println("执行完毕~~~~~~~~~");
}
主要的方法 PreparedStatement 类中的addBatch()、executeBatch();、clearBatch()这三个方法。
三 获取自增长列的ID号
public static void getAuotKey() throws SQLException{
String sql="INSERT INTO team(name,slogan,leader) values(?,?,?)";
Connection conn=SqlHelper.getConnection();
PreparedStatement stmt= conn.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
stmt.setString(1,"yyy");
stmt.setString(2, "gggg");
stmt.setString(3,"fffff");
stmt.executeUpdate();
///获取自动增长的咧
ResultSet res =stmt.getGeneratedKeys();
while(res.next()){
System.out.println(res.getString(1));
}
四 封装通用的JDBC操作方法
private static Connection conn;
private static PreparedStatement stmt;
private static ResultSet set;
public static String drive;
public static String username;
public static String password;
public static String url;
/**
* sql:传入的slq语句
* param 传入的参数 没有参数穿入Null
* [@return](http://my.oschina.net/u/556800) 返回boolean 值true 或者false
* */
public static boolean insert(String sql,Object[] param){
int res=-1;
boolean result=false;
if(sql!=null && !"".equals(sql.trim())){
try {
//获取连接
conn=getConnection();
//创建执行单元
stmt=conn.prepareStatement(sql);
if(param!=null&¶m.length>0){
//获取占位符 得到参数的个数
int count=stmt.getParameterMetaData().getParameterCount();
for(int i=0;i<count;i++){
stmt.setObject(i+1, param[i]);
}
}
//执行更新
stmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
Distory(conn, stmt);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return result;
}
/**
* sql:传入的sql语句
* param:传入的参数
* t:类对象
* [@throws](http://my.oschina.net/throws) SQLException
* [@throws](http://my.oschina.net/throws) IllegalAccessException
* [@throws](http://my.oschina.net/throws) InstantiationException
* [@throws](http://my.oschina.net/throws) InvocationTargetException
* */
public static <T> List<T> query(String sql,Object[] param,Class<T> clazz) throws SQLException, InstantiationException, IllegalAccessException, InvocationTargetException{
List<T> list=new ArrayList();
T t=null;
if(sql!=null && !"".equals(sql.trim())){
conn=getConnection();
stmt=conn.prepareStatement(sql);
if(param!= null && param.length>0){
for(int i=0;i>param.length;i++){
stmt.setObject(i+1, param[i]);
}
}
}
//执行查询
set= stmt.executeQuery();
ResultSetMetaData rsmd =stmt.getMetaData();
int columnCount= stmt.getMetaData().getColumnCount();
while(set.next()){
t=clazz.newInstance();
// 7. 遍历每一行的每一列, 封装数据
for (int i=0; i<columnCount; i++) {
// 获取每一列的列名称
String columnName = rsmd.getColumnName(i + 1);
// 获取每一列的列名称, 对应的值
Object value = set.getObject(columnName);
// 封装: 设置到t对象的属性中 【BeanUtils组件】
BeanUtils.copyProperty(t, columnName, value);
}
// 把封装完毕的对象,添加到list集合中
list.add(t);
}
return list;
}
/**
* 加载数据库驱动
* */
static{
try {
Properties p=new Properties();
InputStream ins= SqlHelper.class.getResourceAsStream("/db.propertise");
p.load(ins);
drive=p.getProperty("Driver");
username=p.getProperty("user");
password=p.getProperty("password");
url=p.getProperty("url");
Class.forName(drive);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 获取连接
* */
public static Connection getConnection() throws SQLException{
conn=DriverManager.getConnection(url, username, password);
return conn;
}
/**
* 销毁对象
* [@throws](https://my.oschina.net/throws) SQLException
* */
public static void Distory(Connection conn,Statement stmt) throws SQLException{
if(conn!=null)
conn.close();
if(stmt!=null)
stmt.close();
}
}