package org.cric.other;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class DBUtils {
private String driverName ="com.mysql.jdbc.Driver";//MySql驱动
private final String url = "jdbc:mysql://localhost:3306/users";//users表示数据库
private final String username = "root";
private final String password = "root";
private Connection con=null;
private Statement stmt=null;
private ResultSet rs=null;
/**
* 加载数据库驱动
*/
public DBUtils(){
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 连接数据库
* @return
* @throws SQLException
*/
public Connection getConnection() throws SQLException{
if(con==null || con.isClosed())
con=java.sql.DriverManager.getConnection(url,username,password);
return con;
}
/**
* 执行数据库操作-查
* @param sqlStr
* @return
*/
public ResultSet executeQuery(String sqlStr){
if(sqlStr==null || sqlStr.length()==0)
{
return null;
}
try {
this.getConnection();
stmt=con.createStatement();
rs=stmt.executeQuery(sqlStr);
return rs;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
/**
* 执行数据库操作---增,删,改
* @param sqlStr
* @return
*/
public boolean executeUpdate(String sqlStr){
if(sqlStr==null || sqlStr.length()==0)
{
return false;
}
try {
this.getConnection();
stmt=con.createStatement();
stmt.executeUpdate(sqlStr);
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}finally{
if(stmt!=null)
try {
stmt.close();
stmt=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(con!=null)
try {
con.close();
con=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 关闭stmt资源
*/
public void closeStmt(){
if(stmt!=null)
try {
stmt.close();
stmt=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 关闭con资源
*/
public void closeConnetion(){
if(con!=null)
try {
con.close();
con=null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 多条数据库更新--事务
* @param al
* @return
*/
public boolean executeUpdates(ArrayList<String> al)
{
if(al==null||al.size()==0)
{
return false;
}
try
{
this.getConnection();
this.con.setAutoCommit(false);
stmt=con.createStatement();
for(int i=0;i<al.size();i++){
stmt.addBatch(al.get(i));
}
stmt.executeBatch();
this.con.commit();
this.con.setAutoCommit(true);
return true;
}
catch(SQLException ex)
{
ex.printStackTrace();
try {
if(con!=null)
con.rollback();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}finally{
try {
if (stmt != null)
{
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (con != null)
{
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}