import java.sql.*;
public class DBUtilUtils {
public static Connection getConnection() {
String url = "jdbc:mysql://127.0.0.1:3306/itcat?useSSL=false";
String user = "root";
String psd = "123456";
String driverName = "com.mysql.jdbc.Driver";
Connection conn = null;
try {
//创建驱动实例
Class clazz = Class.forName(driverName);
Driver driver = (Driver) clazz.newInstance();
//注册驱动
DriverManager.registerDriver(driver);
//获取连接
conn = DriverManager.getConnection(url,user,psd);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void closeAll(Connection conn, Statement statement,ResultSet rs){
if (conn!=null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
if (statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
反射的应用,使用反射来给对象赋值
import java.lang.reflect.Field;
import java.sql.*;
public class Test_data {
public <T> T getInstane(Class<T> clazz, String sql, Object ...args){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = DBUtilUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
//prepareStatement的占位符是从1开始的
ps.setObject(i+1,args[i]);
}
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int coluncount = rsmd.getColumnCount();
if (rs.next()){
T t = clazz.newInstance();
for (int i = 0; i < coluncount; i++) {
//获取列值
Object columVal = rs.getObject(i+1);
//获取列名
String columName = rsmd.getColumnLabel(i+1);
//使用反射给对象的相应值赋值
Field declaredField = clazz.getDeclaredField(columName);
//暴力反射,即便是私有变量也可以赋值
declaredField.setAccessible(true);
declaredField.set(t,columVal);
}
return t;
}
} catch (Exception e) {
e.printStackTrace();
}finally {
DBUtilUtils.closeAll(conn,ps,rs);
}
return null;
}
}