public class JdbcUtil {
public JdbcUtil() {
}
private static Properties properties = new Properties();
private static DataSource dds;
static {
try {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
InputStream is = cl.getResourceAsStream("db.properties");
properties.load(is);
dds = DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
try {
Connection conn = dds.getConnection();
return conn;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("连接数据库失败");
}
}
public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (ps != null) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public static int insert(Object obj) {
Connection con = JdbcUtil.getConnection();
// insert into XXX(xx,xx) value(?,?)StringBuilder sb = new StringBuilder();
sb.append("insert into ");
@SuppressWarnings("unchecked")
Class clz = (Class) obj.getClass();
String simplename = clz.getSimpleName();
sb.append(simplename + "(");
Field[] field1 = clz.getDeclaredFields();
for (Field field : field1) {
String fieldname = field.getName();
sb.append(fieldname);
sb.append(",");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(") value(");
for (@SuppressWarnings("unused")
Field field : field1) {
sb.append("?");
sb.append(",");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(")");
String sql = sb.substring(0);
System.out.println(sql);
PreparedStatement ps = null;
try {
ps = con.prepareStatement(sql);
for (int i = 0; i < field1.length; i++) {
String fieldname = field1[i].getName();
String name = "get" + fieldname.toUpperCase().substring(0, 1)
+ fieldname.substring(1, fieldname.length());
System.out.println(name);
Method getObj = clz.getMethod(name);
Object value = getObj.invoke(obj);
System.out.println(value);
ps.setObject(i + 1, value);
}
return ps.executeUpdate();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(con, ps, null);
}
return 0;
}
// delete from xx where id = ?@SuppressWarnings({})
public static int delete(Integer id, Object obj) {
Connection conn = JdbcUtil.getConnection();
PreparedStatement ps = null;
StringBuilder sb = new StringBuilder();
Class> clz = obj.getClass();
sb.append("delete from ");
String simpleName = clz.getSimpleName();
sb.append(simpleName);
sb.append(" where id = ?");
String sql = sb.toString();
System.out.println(sql);
try {
ps = conn.prepareStatement(sql);
ps.setObject(1, id);
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(conn, ps, null);
}
return 0;
}
//String sql = "update student set name = ?,age = ? where id = ?";@SuppressWarnings("resource")
public static int update(Object obj) {
Connection conn = JdbcUtil.getConnection();
PreparedStatement ps = null;
StringBuilder sb = new StringBuilder();
@SuppressWarnings("unchecked")
Class clz = (Class) obj.getClass();
sb.append("update ");
sb.append(obj.getClass().getSimpleName());
sb.append(" set ");
Field[] fields = clz.getDeclaredFields();
for (Field field : fields) {
if (!field.getName().equals("id")) {
sb.append(field.getName() + "=?,");
}
}
sb.deleteCharAt(sb.length() - 1);
sb.append(" where id = ?");
System.out.println(sb.toString());
// 獲取方法,getName,getAge,getIdField[] fields2 = clz.getDeclaredFields();
Method method = null;
try {
ps = conn.prepareStatement(sb.toString());
for (int i = 0; i < fields2.length; i++) {
String m = fields2[i].getName();
String upper = m.toUpperCase().substring(0, 1);
String theRest = m.substring(1, m.length());
String methodName = "get" + upper + theRest;
System.out.println(methodName);
method = clz.getMethod(methodName);
Object obj2 = method.invoke(obj);
ps.setObject(i + 1, obj2);
}
return ps.executeUpdate();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(conn, ps, null);
}
return 0;
}
@SuppressWarnings({ "finally", "resource" })
public static Object selectByprimaryKey(Integer id, Object obj) {
// sql語句: select * from XXX where id = ?Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
StringBuilder sb = new StringBuilder();
Class clz = (Class) obj.getClass();
conn = JdbcUtil.getConnection();
sb.append("select * from " + obj.getClass().getSimpleName() + " where id = ?");
try {
// 執行sql語句ps = conn.prepareStatement(sb.toString());
// 賦值ps.setInt(1, id);
// 開始查詢rs = ps.executeQuery();
// 尋找Set方法並執行..Method[] methods = clz.getMethods();
if (rs.next()) {
for (Method method : methods) {
String methodName = method.getName();
if (methodName.startsWith("set")) {
System.out.println(methodName);
String ziduan = methodName.substring(3, methodName.length()).toLowerCase();
System.out.println(ziduan);
Object arg = rs.getObject(ziduan);
method.invoke(obj, arg);
}
}
}
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(conn, ps, rs);
return obj;
}
}
public static List selectList(Object obj) {
Connection conn = JdbcUtil.getConnection();
PreparedStatement ps = null;
StringBuilder sb = new StringBuilder();
Class clz = (Class) obj.getClass();
ResultSet rs = null;
List list = new ArrayList();
// 組合sql語句 select * from XXXsb.append("select * from ");
sb.append(clz.getSimpleName());
try {
// 執行sql語句ps = conn.prepareStatement(sb.toString());
// 開始查詢rs = ps.executeQuery();
// 尋找方法Method[] methods = clz.getMethods();
while (rs.next()) {
// 每一次循環創建一次對象Object objtest = clz.newInstance();
for (Method method : methods) {
String methodName = method.getName();
if (methodName.startsWith("set")) {
// 獲取字段,全小寫String words = methodName.substring(3, methodName.length()).toLowerCase();
System.out.println(words);
// 查找字段相對應的值Object value = rs.getObject(words);
// 在用相對應的值作爲參數用到set方法中method.invoke(objtest, value);
}
}
list.add((T) objtest);
}
return list;
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
return null;
}
}