數據庫連接是件很麻煩的事,特別是封裝數據庫,讓我們java編程不再有煩惱
代碼如下:
import java.sql.Connection;
public class JDBC {
private final String drive="com.mysql.jdbc.Driver";
private final String url="jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8";
private final String name="root";
private final String password="123456";
private Connection con=null;
public JDBC(){//構造方法加載數據庫驅動
try {
Class.forName(drive).newInstance();
} catch (Exception e) {
System.out.println("數據庫加載失敗!");
}
}
public boolean creatConnection(){//創建數據庫連接
try {
con=DriverManager.getConnection(url,name,password);
con.setAutoCommit(true);
} catch (SQLException e) {
}
return true;
}
public boolean executeUpdate(String sql){//對數據表的增加,修改和刪除的操作
if(con==null){
creatConnection();
}
try{
Statement s=con.createStatement();
int i=s.executeUpdate(sql);
System.out.println("操作成功,所影響的記錄數爲:"+String.valueOf(i));
return true;
}catch(Exception e){
return false;
}
}
public ResultSet executeQuery(String sql){//數據庫的查詢操作
ResultSet rs;
try{
if(con==null){
creatConnection();
}
Statement s=con.createStatement();
rs=s.executeQuery(sql);
return rs;
}catch(Exception e){
return null;
}
}
public void closeConnection(){//關閉數據庫連接
if(con==null){
try {
con.close();
}catch (SQLException e) {
}
}
}
basedao封裝
import java.lang.reflect.Field;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
* 基礎DAO類
* @author LYF
*/
public class BaseDao {
/**
* 連接數據庫的URL
*/
private static String url;
/**
* 登錄數據庫用戶名
*/
private static String user;
/**
* 登錄數據庫密碼
*/
private static String password;
/**
* 所有線程共享的線程容器
*/
private static ThreadLocal<Map<String, Object>> threadLocal = null;
//靜態塊中實例化線程容器並裝載數據庫驅動
static {
init();
}
private static void init(){
threadLocal = new ThreadLocal<Map<String, Object>>();
try {
Properties pro=new Properties();
pro.load(ClassLoader.getSystemResource("db.properties").openStream());
user=pro.getProperty("user");
password=pro.getProperty("password");
url=pro.getProperty("url");
Class.forName(pro.getProperty("driver"));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取連接對象Connection
* @return
* @throws SQLException
*/
public Connection getConnection() throws SQLException {
//從線程中取出保存數據
Map<String, Object> threadMap = threadLocal.get();
if (null == threadMap) {
threadMap = new HashMap<String, Object>();
threadLocal.set(threadMap);
}
Connection conn = (Connection) threadMap.get("conn");
if (null == conn || conn.isClosed()) {
conn = DriverManager.getConnection(url, user, password);
threadMap.put("conn", conn);
}
return conn;
}
/**
* 泛型方法(執行查詢DQL)
* @param <T>
* @param cla
* @param sql
* @param params
* @return
* @throws SQLException
*/
public <T> List<T> executeQuery(Class<T> cla, String sql, Object... params)
throws SQLException {
//獲取連接對象
Connection conn = this.getConnection();
//創建預編譯語句對象
PreparedStatement pstat = conn.prepareStatement(sql);
// 將產生的語句對象放置到線程中
PreparedStatement oldpstat = (PreparedStatement) threadLocal.get().put("pstat", pstat);
//如果線程中有舊的語句對象則關閉它
if (null != oldpstat)oldpstat.close();
// 設置預編譯佔位符參數(參數從1開始)
for (int i = 0; i < params.length; i++) {
pstat.setObject(i + 1, params[i]);
}
List<T> list = new ArrayList<T>();
//執行查詢返回結果集
ResultSet res = pstat.executeQuery();
//將結果集放置到線程中
ResultSet oldRes = (ResultSet) threadLocal.get().put("res", res);
//如果線程中有舊的結果集則關閉它
if (null != oldRes)oldRes.close();
//獲取結果集元數據
ResultSetMetaData rsmd=res.getMetaData();
//返回結果集中字段數量(列的數量)
int colNum=rsmd.getColumnCount();
try {
T t = null;
while (res.next()) {//遍歷結果集中的所有記錄
t = cla.newInstance();//每循環一次生成一個實體對象
for(int i=0;i<colNum;i++){//循環記錄中的每個字段
//取出字段的名稱
String fieldName=rsmd.getColumnLabel(i+1);
//取出字段的值
Object object=res.getObject(fieldName);
//獲取實體類的字段
Field field=cla.getDeclaredField(fieldName);
//打開private權限的字段訪問權限
field.setAccessible(true);
//設置實體類對象字段屬性值
field.set(t, object);
}
list.add(t);//將實體對象添加的返回列表中
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
return list;
}
/**
* 執行增刪改(DML)
* @param sql
* @param params
* @return
*/
public int executeUpdate(String sql,Object... params) throws SQLException{
Connection conn = this.getConnection();
PreparedStatement pstat = conn.prepareStatement(sql);
PreparedStatement oldpstat = (PreparedStatement) threadLocal.get().put("pstat", pstat);
if (null != oldpstat)oldpstat.close();
for (int i = 0; i < params.length; i++) {
pstat.setObject(i + 1, params[i]);
}
//執行DML返回影響行數
return pstat.executeUpdate();
}
/**
* 執行增加(insert)並且返回主鍵
* @param sql
* @param params
* @return
*/
public int[] executeInsert(String sql,Object... params) throws SQLException{
Connection conn = this.getConnection();
PreparedStatement pstat = conn.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
PreparedStatement oldpstat = (PreparedStatement) threadLocal.get().put("pstat", pstat);
if (null != oldpstat)oldpstat.close();
for (int i = 0; i < params.length; i++) {
pstat.setObject(i + 1, params[i]);
}
//返回影響行數(就是插入的記錄數量)
int count=pstat.executeUpdate();
//定義保存數據庫生成的主鍵的數組
int[] keys=new int[count];
//獲取主鍵結果集
ResultSet res=pstat.getGeneratedKeys();
//將結果集放置到當前線程中
ResultSet oldRes = (ResultSet) threadLocal.get().put("res", res);
if(null!=oldRes)oldRes.close();
//遍歷結果集,將結果集合中的所有主鍵取出來放到數組中
for(int i=0;res.next();i++){
keys[i]=res.getInt(1);
}
return keys;
}
/**
* 關閉所有的連接(從線程中取出所有JDBC對象並關閉它們)
* @throws SQLException
*/
public void closeAll() throws SQLException{
Map<String,Object> map=threadLocal.get();
Connection conn=(Connection)map.get("conn");
PreparedStatement pstat=(PreparedStatement)map.get("pstat");
ResultSet res=(ResultSet)map.get("res");
if(null!=res)res.close();
if(null!=pstat)pstat.close();
if(null!=conn)conn.close();
}
}
}
百度貼吧歡迎提問?