日期:2014-05-20 浏览次数:20819 次
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* database DEFAULT CHARACTER SET utf8
*
*/
public final class JdbcUtil {
private static final String url = "jdbc:mysql://localhost:3306/dbdemo?useUnicode=true&characterEncoding=UTF-8";
private static final String user = "root";
private static final String password = "sa";
/**
* 注册
*
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection register(){
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection connection = null;
try {
connection = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
public static void freeResource(Connection connection, Statement statement,
ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class BaseDao {
/**
* 执行sql语句,如果第一个结果是 ResultSet 对象则返回List
* @param sql
* @return
*/
public List execute(String sql, List params){
if (sql == null || sql.equals("")) {
return null;
}
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet rs = null;
boolean flag = false;
try {
connection = JdbcUtil.register();
connection.setAutoCommit(false);// 关闭自动提交事务(开启事务)
preparedStatement = connection.prepareStatement(sql);
if(params != null && params.size() > 0){