package com.tao.utils;
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 javax.sql.DataSource;
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;
}
//增删改通用方法
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;
}
//设值通用方法
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;
}
}