德魯伊數據庫鏈接

package com.tao.utils;java

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;spring

import javax.sql.DataSource;sql

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;數據庫

/**
* @author 陳建
* @描述:dao基礎類
* 2018-10-25下午2:54:57
*/
@Repository
public class BaseDao {
//四大金剛
@Autowired
private DataSource dataSource;
//獲取數據庫鏈接
public Connection getConnection() {
try {
return dataSource.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;

}

//查詢通用方法
public List<Map<String,Object>> executeQuery(String sql,Object...params) {
List<Map<String,Object>> objList= new ArrayList<Map<String,Object>>();
Connection conn = getConnection();
PreparedStatement ps=null;
ResultSet rs=null;
try {
ps = conn.prepareStatement(sql);
ps = setParams(ps, params);
//執行sql
rs = ps.executeQuery();
//獲取表元數據信息
ResultSetMetaData metaData = rs.getMetaData();
//解析結果集
while(rs.next()){
Map<String,Object> row= new HashMap<String, Object>();
//metaData.getColumnCount()獲取列數
for (int i = 0; i < metaData.getColumnCount(); i++) {
row.put(metaData.getColumnName(i+1), rs.getObject(i+1));
}
objList.add(row);
}
} catch (SQLException e) {
e.printStackTrace();
}
return objList;get

}
//增刪改通用方法
public boolean executeUpdate(String sql,Object...params) {
Connection conn = getConnection();
PreparedStatement ps=null;
try {
ps = conn.prepareStatement(sql);
ps = setParams(ps, params);
//執行sql
int ret = ps.executeUpdate();
if(ret>0){
System.out.println("操做成功!");
return true;

}else
{
System.out.println("操做失敗!");
return false;
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;it

}
//設值通用方法
public PreparedStatement setParams(PreparedStatement ps,Object...params) {
if(params!=null){
for (int i = 0; i < params.length; i++) {
try {
ps.setObject(i+1, params[i]);
} catch (SQLException e) {
e.printStackTrace();
}

}
}

return ps;io

}
class

}import

相關文章
相關標籤/搜索