import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
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.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.apache.commons.beanutils.BeanUtils;
public class JdbcUtils {
private static String Driver="";
private static String url="";
private static String username="";
private static String password="";
static {
//获得一个资源文件对象
Properties p = new Properties();
try {
//加载资源文件
p.load(JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
Driver = p.getProperty("Driver");
url = p.getProperty("url");
username = p.getProperty("username");
password = p.getProperty("password");
//加载驱动程序
Class.forName(Driver);
} catch (Exception e) {
e.printStackTrace();
}
}
private static Connection getConnection(){
Connection conn = null;
try {
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
} return conn;
}
//封装列表User
public static List<?> getList(String sql,Class<?> clazz) {
System.out.println(sql);
Connection conn = null;
PreparedStatement ps = null;
ResultSet re = null;
conn = getConnection();
List<Object> list = new ArrayList();
try {
//创建sql预编译器
ps = conn.prepareStatement(sql);
//执行sql语句
re = ps.executeQuery();
//从执行完成的结果中得到数据
ResultSetMetaData data = re.getMetaData();
//得到数据的总列数
int i = data.getColumnCount();
while(re.next()){
Object obj = clazz.newInstance();
for (int j = 1; j <=i; j++) {
BeanUtils.copyProperty(obj, data.getColumnName(j),re.getObject(j));
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
close(conn, ps, re);
}
return list;
}
//修改查询
public static Object findById(String sql,Class<?> clazz){
//获取数据库连接
Connection conn = null;
PreparedStatement ps = null;
Object obj = null;
conn = getConnection();
try {
ps = conn.prepareStatement(sql);
ResultSet re = ps.executeQuery();
ResultSetMetaData data = re.getMetaData();
int i = data.getColumnCount();
if(re.next()){
obj = clazz.newInstance();
for (int j = 1; j <= i; j++) {
BeanUtils.copyProperty(obj, data.getColumnName(j), re.getObject(j));
}
}
} catch (Exception e) {
e.printStackTrace();
} return obj;
}

//添加/删除/修改
public static int excute(String sql){
int i = 0;
Connection conn = null;
PreparedStatement ps = null;
conn = getConnection();
try {
ps = conn.prepareStatement(sql);
i = ps.executeUpdate();
if(i>0){
System.out.println("成功");
}
} catch (Exception e) {
e.printStackTrace();
}
return i;
}


//封装关流
private static void close(Connection conn,PreparedStatement ps,ResultSet re){
try {
if(conn!=null)
conn.close();
if(ps!=null)
ps.close();
if(re!=null)
re.close();
} catch (SQLException e) {
e.printStackTrace();
}

}
}