首页 > 代码库 > DButils工具类能够用来获取数据库连接向数据库插入更新删除对象
DButils工具类能够用来获取数据库连接向数据库插入更新删除对象
package com.ctl.util; import java.awt.Color; import java.awt.Font; import java.awt.Insets; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.*; import java.lang.reflect.*; import java.sql.*; import java.util.*; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JTextField; /** * @author Administrator * @category */ public class DButils { private static String driver; private static String url; private static String username; private static String password; private static Connection conn; private static ThreadLocal<Connection> connHolder = new ThreadLocal<Connection>(); static { driver = RegisterUtil.getStringFromSystemRoot("mysql.driver"); url = RegisterUtil.getStringFromSystemRoot("mysql.url"); username = RegisterUtil.getStringFromSystemRoot("mysql.username"); password = RegisterUtil.getStringFromSystemRoot("mysql.password"); try { Runtime.getRuntime().exec("net start mysql"); } catch (IOException e) { e.printStackTrace(); } } static class KeyValue { Object key; Object value; public Object getKey() { return key; } public void setKey(Object key) { this.key = key; } public Object getValue() { return value; } public void setValue(Object value) { this.value = http://www.mamicode.com/value;":" + this.value; } } /** * * @return Connection * @throws SQLException * @throws ClassNotFoundException */ public static Connection getConnection() { conn = connHolder.get(); try { if (conn == null || conn.isClosed()) { Class.forName(driver); conn = DriverManager.getConnection(url, username, password); conn.setAutoCommit(false); connHolder.set(conn); } } catch (Exception e) { init(); e.printStackTrace(); } return conn; } /** * @category 依据sql得到记录总数 * @param sql * @return int 假设返回-1代表出错 */ public static int getCount(String sql) { try { ResultSet rs = getConnection().createStatement().executeQuery(sql); if (rs.next()) { return rs.getInt(1); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return -1; } /** * @see 获取某张表的总记录数 * @param c * Person.class * @return -1 出错 >=0 right */ public static int getCount(Class c) { String tableName = c.getSimpleName().toLowerCase();// person 表的名字 if (!isTableExist(tableName)) { System.err.println("表‘" + tableName + "‘不存在"); return -1; } try { ResultSet rs = getConnection().prepareStatement( "select count(" + getColumns(c).get(0) + ") from " + tableName).executeQuery(); if (rs.next()) { return rs.getInt(1); } } catch (Exception e) { e.printStackTrace(); } return -1; } public static void init(){ Font fontGlobal = new Font("楷体", 11, 10); JFrame jf=new JFrame("数据库初始化操作"); jf.setVisible(true); jf.setBounds(600 , 260, 266, 166); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setResizable(false); JPanel jpanel=new JPanel(); jpanel.setBounds(0, 0, 300, 600); jf.add(jpanel); jpanel.setBackground(new Color(199, 237, 204)); jpanel.setLayout(null); // JLabel jls1 = new JLabel("mysql 数据库初始化操作"); // jls1.setBounds(30, 0, 140, 20); // jpanel.add(jls1); // jls1.setFont(fontGlobal); JLabel jls2 = new JLabel("主机名/ip:"); jls2.setBounds(0, 5, 50, 45); jpanel.add(jls2); jls2.setFont(fontGlobal); // IP框 final JTextField jtfip = new JTextField(18); jtfip.setBounds(50, 17, 100, 20); jpanel.add(jtfip); jtfip.setText("127.0.0.1"); JLabel jls3 = new JLabel("端口:"); jls3.setBounds(155, 5, 50, 45); jpanel.add(jls3); jls3.setFont(fontGlobal); // 端口框 final JTextField jtfport = new JTextField(15); jtfport.setBounds(180, 17, 45, 20); jpanel.add(jtfport); jtfport.setText("3306"); JLabel jls4= new JLabel("用户名:"); jls4.setBounds(16, 35, 50, 45); jpanel.add(jls4); jls4.setFont(fontGlobal); final JTextField jtfip1 = new JTextField(18); jtfip1.setBounds(50, 46, 58, 20); jpanel.add(jtfip1); jtfip1.setText("root"); JLabel jls5= new JLabel("密码:"); jls5.setBounds(125, 35, 50, 45); jpanel.add(jls5); jls5.setFont(fontGlobal); // 端口框 final JPasswordField jtfport1 = new JPasswordField(15); jtfport1.setBounds(150, 46,75, 20); jpanel.add(jtfport1); jtfport1.setText("root"); JLabel jls6= new JLabel("数据库名:"); jls6.setBounds(6, 65, 50, 45); jpanel.add(jls6); jls6.setFont(fontGlobal); // IP框 final JTextField jtfip11 = new JTextField(18); jtfip11.setBounds(50, 77, 58, 20); jpanel.add(jtfip11); jtfip11.setText("test"); JLabel jls51= new JLabel("编码:"); jls51.setBounds(125, 65, 50, 45); jpanel.add(jls51); jls51.setFont(fontGlobal); // 端口框 final JTextField jtfport11 = new JTextField(15); jtfport11.setBounds(150, 77,75, 20); jpanel.add(jtfport11); jtfport11.setText("utf-8"); final JButton linkBtn = new JButton("初始化DButils工具类"); linkBtn.setBounds(56, 111, 150, 20); jpanel.add(linkBtn); linkBtn.setMargin(new Insets(0,0,0,0));// 这样设置button中的字体与button无上下边距 linkBtn.setFont(fontGlobal); MouseAdapter linkServerListener = new MouseAdapter() { public void mouseClicked(MouseEvent e) { //linkClick(e);// 点击连接 String ip=jtfip.getText().trim(); int port=Integer.parseInt(jtfport.getText().trim()); String username=jtfip1.getText().trim(); String password=jtfport1.getText().trim(); String databaseName=jtfip11.getText().trim(); String code=jtfport11.getText().trim(); String mysqlDriver="com.mysql.jdbc.Driver"; String mysqlUrl="jdbc:mysql://"+ip+":"+port+"/"+databaseName +"?unicode\\=true&characterEncoding\\="+code; RegisterUtil.putStringSystemRoot("mysql.driver", mysqlDriver); RegisterUtil.putStringSystemRoot("mysql.url", mysqlUrl); RegisterUtil.putStringSystemRoot("mysql.username", username); RegisterUtil.putStringSystemRoot("mysql.password", password); System.out.println(RegisterUtil.getStringFromSystemRoot("mysql.driver")); System.out.println(mysqlUrl); System.out.println(username); System.out.println(password); try { conn = DriverManager.getConnection(RegisterUtil.getStringFromSystemRoot("mysql.url"), RegisterUtil.getStringFromSystemRoot("mysql.username"), RegisterUtil.getStringFromSystemRoot("mysql.password")); if(conn!=null) { linkBtn.setText("初始化成功!请关闭窗口"); } } catch (Exception e2) { // TODO: handle exception } //System.exit(0); } }; linkBtn.addMouseListener(linkServerListener); } /** * @category close Connection * @throws SQLException */ public static void close() throws SQLException { conn.close(); connHolder.set(null); } public static int createTable(Class c) { String tableName = c.getSimpleName().toLowerCase();// person return 0; } /** * * @param c * 參数比如Person.class * @param obj * 參数比如 person obj为某一实例对象 // Person person=new Person(); * @category 该方法用于向数据库中插入条数据 插入的对象是一个实体类的对象 */ public static void insertEntity(Class c, Object obj) { // System.out.println("1"); if (obj == null || c.getSimpleName().equals(obj.getClass().getName())) return; Field[] fields = obj.getClass().getDeclaredFields(); int fieldSize = fields.length; String tableName = c.getSimpleName().toLowerCase();// person String[] types1 = { "int", "java.lang.String", "boolean", "char", "float", "double", "long", "short", "byte", "date" }; String[] types2 = { "java.lang.Integer", "java.lang.String", "java.lang.Boolean", "java.lang.Character", "java.lang.Float", "java.lang.Double", "java.lang.Long", "java.lang.Short", "java.lang.Byte", "java.util.Date" }; StringBuffer sql = new StringBuffer("replace into " + tableName + " values("); for (int i = 0; i < fieldSize; i++) { sql.append("?,"); } sql.deleteCharAt(sql.length() - 1); sql.append(")"); System.out.println(sql); PreparedStatement ps = null; try { ps = getConnection().prepareStatement(sql.toString()); for (int j = 0; j < fieldSize; j++) { fields[j].setAccessible(true); for (int i = 0; i < types1.length; i++) { if (fields[j].getType().getName() .equalsIgnoreCase(types1[i]) || fields[j].getType().getName() .equalsIgnoreCase(types2[i])) { if (fields[j].get(obj) != null && !"".equals(fields[j].get(obj)) && !"null".equals(fields[j].get(obj))) { System.out.print(fields[j].getName() + ":" + fields[j].get(obj) + " "); ps.setObject(j + 1, fields[j].get(obj)); } else { System.out.print(fields[j].getName() + ":" + fields[j].get(obj) + " "); ps.setObject(j + 1, null); } } } } ps.executeUpdate(); getConnection().commit(); System.out.println("\nsql:" + ps.toString().split(":")[1].trim()); } catch (Exception e1) { e1.printStackTrace(); } } /** * @category 依据传入的主键值返回一个实体对象 * @param c * for example Person.class * @param primaryKeys * primaryKeys为主键,參数顺序和表中保持一致 假设id, name 为主键 类名为Person 则 * getEntity(Person.class,1,"name") * @return Object */ public static Object getEntity(Class c, Object... primaryKeys) { PreparedStatement ps = null; ResultSet rs = null; DatabaseMetaData dmd = null; Object obj = null;// 要返回的对象 String tableName = c.getSimpleName().toLowerCase();// person 表的名字 List primaryKeyNameList = new ArrayList();// 存放从表中获取的主键 Field[] fields = c.getFields();// 获取全部的属性 Method[] methods = null; if (fields.length == 0) {// 当类的属性都是private时 // fields=c.getDeclaredFields();//获取全部的private属性 methods = c.getDeclaredMethods();// 获取get set 方法 } StringBuilder sql = new StringBuilder("select * from " + tableName + " where "); try { obj = c.newInstance(); if (!isTableExist(tableName)) { System.err.println("表不存在"); return obj; } dmd = getConnection().getMetaData(); rs = dmd.getPrimaryKeys(null, null, tableName); while (rs.next()) {// 获取全部的主键 sql.append(rs.getObject(4) + "=?
"); sql.append(" and "); primaryKeyNameList.add(rs.getObject(4));// 将从表中获取的 主键字段存到 list中, // 主键位于表中第几列=rs.getString(5) } sql.delete(sql.length() - 4, sql.length()); if (!sql.toString().contains("where")) { System.err.println("没有找到主键"); return obj; } ps = (PreparedStatement) getConnection().prepareStatement( sql.toString()); for (int l = 0; l < primaryKeyNameList.size(); l++) { ps.setObject(l + 1, primaryKeys[l]); } rs = ps.executeQuery(); System.out.println(ps.toString().split(":")[1]); List<String> tableColumns = getColumns(c); if (rs.next()) { if (fields.length > 0) {// 假设类 的属性为public for (int k = 0; k < fields.length; k++) { fields[k].set(obj, rs.getObject(k + 1)); } } else {// 假设类 的属性为private for (int k = 0; k < methods.length; k++) { for (int i = 0; i < tableColumns.size(); i++) { if (methods[k].getName().equalsIgnoreCase( "set" + tableColumns.get(i))) { methods[k].invoke(obj, rs.getObject(tableColumns.get(i))); } } } } } rs.close(); ps.close(); rs = null; ps = null; } catch (Exception e) { e.printStackTrace(); } finally { } return obj; } /** * * @param tableName * 标的名字 * @category 表不存在 1表存在 * @return 0表不存在 >=1表存在 */ public static boolean isTableExist(String tableName) { int v = getCount("SELECT count(table_name) FROM information_schema.TABLES WHERE table_name=‘" + tableName + "‘ "); if (v >= 1) { return true; } else { System.err.println("表 不存在 table not exist"); return false; } } /** * * @category 获取某个表中全部的列名 * @param c * Person.class (类名与表名一致) * @return List */ public static List<String> getColumns(Class c) { List<String> list = new ArrayList<String>(); String tableName = c.getSimpleName().toLowerCase();// person 表的名字 if (!isTableExist(tableName)) { System.err.println("talbe is not exist"); return list; } String sql = "select COLUMN_NAME from information_schema.columns where table_name=‘" + tableName + "‘"; try { ResultSet rs = getConnection().createStatement().executeQuery(sql); while (rs.next()) { if (!list.contains(rs.getString(1))) { list.add(rs.getString(1));// 防止不同数据库中有同样的表名 } } } catch (Exception e) { e.printStackTrace(); } return list; } /** * @category 返回数据库的名字 * @param Person * .class * @return database name */ public static String getDatabaseName(Class c) { String tableName = c.getSimpleName().toLowerCase();// person 表的名字 try { ResultSet rs = getConnection().getMetaData().getPrimaryKeys(null, null, tableName); if (rs.next()) { System.out.println("database:"+rs.getString(1)); return rs.getString(1); } } catch (Exception e) { e.printStackTrace(); } return null; } /** * @category 返回 int auto_increment的下一个自增值 * @param c * Person。class * @return int 下一个自增值 假设没有则返回null */ public static int getAutoIncremet(Class c) { String tableName = c.getSimpleName().toLowerCase();// person 表的名字 if (!isTableExist(tableName)) { System.err.println("表‘" + tableName + "‘不存在"); return -1; } try { ResultSet rs = getConnection().prepareStatement( "SELECT auto_increment FROM information_schema.`TABLES` WHERE TABLE_SCHEMA=‘" + getDatabaseName(c) + "‘ AND TABLE_NAME=‘" + tableName + "‘").executeQuery(); if (rs.next()) { return rs.getInt(1); } } catch (Exception e) { e.printStackTrace(); } return -1; } /** * @category 查找某一列的全部值 * @param c * Person.class * @param columnName * 要查找的某一列的列名 * @return List<String> 返回某一列的全部值 */ public static List<String> getColumnData(Class c, String columnName) { if (!getColumns(c).contains(columnName)) { System.err.println("列名‘" + columnName + "‘不存在"); return null; } List<String> list = new ArrayList<String>(); String tableName = c.getSimpleName().toLowerCase();// person 表的名字 if (!isTableExist(tableName)) { System.err.println("talbe is not exist"); return list; } String sql = "select " + columnName + " from " + tableName; try { ResultSet rs = getConnection().createStatement().executeQuery(sql); while (rs.next()) { list.add(rs.getString(1)); } } catch (Exception e) { e.printStackTrace(); } return list; } /** * @category 依据条件查询 返回where columnName=value * @param c * Person.class 且Person 全部的属性必须全为为public类型或者全部为private * @param columnName * 表中的某字段 * @param value * columnName相应的值 * @return List */ public static List getEntitys(Class c, String columnName, Object value) { if (!getColumns(c).contains(columnName)) { System.err.println("列名‘" + columnName + "‘不存在"); return null; } List list = new ArrayList(); PreparedStatement ps = null; ResultSet rs = null; String tableName = c.getSimpleName().toLowerCase();// person 表的名字 Field[] fields = c.getFields();// 获取全部的public属性 Method[] methods = null; if (fields.length == 0) { fields = c.getDeclaredFields();// 获取全部的private属性 methods = c.getDeclaredMethods();// 获取get set 方法 } StringBuilder sql = new StringBuilder("select * from " + tableName + " where " + columnName + "=?
"); try { if (!isTableExist(tableName)) { System.err.println("表不存在"); return list; } ps = (PreparedStatement) getConnection().prepareStatement( sql.toString()); ps.setObject(1, value); rs = ps.executeQuery(); System.out.println("\n" + ps.toString().split(":")[1]); Object obj = null; while (rs.next()) { obj = c.newInstance(); if (fields.length > 0) {// 假设类 的属性为public for (int k = 0; k < fields.length; k++) { fields[k].setAccessible(true); fields[k].set(obj, rs.getObject(k + 1)); } } else {// 假设类 的属性为private for (int k = 0; k < methods.length / 2; k++) { methods[k * 2].invoke(obj, rs.getObject(k + 1)); } } list.add(obj); } rs.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } finally { rs = null; ps = null; } return list; } /** * @see 获取全部的数据 * @param c * Person.class * @return List全部的数据 */ public static List getAllEntitys(Class c) { String tableName = c.getSimpleName().toLowerCase();// person 表的名字 if (!isTableExist(tableName)) { System.err.println("表‘" + tableName + "‘不存在"); return null; } List list = new ArrayList(); PreparedStatement ps = null; ResultSet rs = null; Field[] fields = c.getFields();// 获取全部的public属性 if (fields.length == 0) { // fields=c.getDeclaredFields();//获取全部的private属性 fields = c.getDeclaredFields();// 获取get set 方法 } StringBuilder sql = new StringBuilder("select * from " + tableName); try { if (!isTableExist(tableName)) { System.err.println("表不存在"); return list; } ps = (PreparedStatement) getConnection().prepareStatement( sql.toString()); rs = ps.executeQuery(); System.out.println("\n" + ps.toString().split(":")[1]); Object obj = null; while (rs.next()) { obj = c.newInstance(); for (int k = 0; k < fields.length; k++) { fields[k].setAccessible(true); fields[k].set(obj, rs.getObject(k + 1)); } list.add(obj); } rs.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } finally { rs = null; ps = null; } return list; } /** * @see 获取数据中的某几条记录 * @param c * Person.class * @param fromNumber * 从数据库的第几条開始(0,1,2。3) * @param number * 从fromNumber開始获取多少行 * @return List */ public static List getEntitysLimit(Class c, int fromNumber, int number) { String tableName = c.getSimpleName().toLowerCase();// person 表的名字 if (!isTableExist(tableName)) { System.err.println("表‘" + tableName + "‘不存在"); return null; } List list = new ArrayList(); PreparedStatement ps = null; ResultSet rs = null; Field[] fields = c.getFields();// 获取全部的public属性 if (fields.length == 0) { // fields=c.getDeclaredFields();//获取全部的private属性 fields = c.getDeclaredFields();// 获取get set 方法 } StringBuilder sql = new StringBuilder("select * from " + tableName) .append(" limit ?
,?
"); try { if (!isTableExist(tableName)) { System.err.println("表不存在"); return list; } ps = (PreparedStatement) getConnection().prepareStatement( sql.toString()); ps.setInt(1, fromNumber); ps.setInt(2, number); rs = ps.executeQuery(); System.out.println("\n" + ps.toString().split(":")[1]); Object obj = null; while (rs.next()) { obj = c.newInstance(); for (int k = 0; k < fields.length; k++) { fields[k].setAccessible(true); fields[k].set(obj, rs.getObject(k + 1)); } list.add(obj); } rs.close(); ps.close(); } catch (Exception e) { e.printStackTrace(); } finally { rs = null; ps = null; } return list; } /** * @category 返回表中全部的主键 * @param c * Person.class * @return list */ public static List<String> getPrimaryKeys(Class c) { String tableName = c.getSimpleName().toLowerCase();// person 表的名字 ResultSet rs = null; List<String> list = new ArrayList<String>(); try { rs = getConnection().getMetaData().getPrimaryKeys(null, null, tableName); while (rs.next()) { list.add(rs.getString(4)); } } catch (Exception e) { e.printStackTrace(); } return list; } /** * @category 依据主键删除数据 * @param c * Person.class * @param primaryKey * 按表中主键删除 假设主键为id。name * 则deleteByPrimaryKey(Person.class,1,"ctl"); */ public static void deleteByPrimaryKey(Class c, Object... primaryKey) { String tableName = c.getSimpleName().toLowerCase();// person 表的名字 List<String> primaryKeysList = getPrimaryKeys(c); StringBuilder sb = new StringBuilder("delete from " + tableName + " where "); for (int i = 0; i < primaryKeysList.size(); i++) { sb.append(primaryKeysList.get(i) + "=? and "); } sb.delete(sb.length() - 4, sb.length()); PreparedStatement ps = null; try { ps = getConnection().prepareStatement(sb.toString()); for (int i = 0; i < primaryKeysList.size(); i++) { ps.setObject(i + 1, primaryKey[i]); } ps.executeUpdate(); getConnection().commit(); System.out.println(ps.toString().split(":")[1].trim()); } catch (Exception e) { e.printStackTrace(); } } /** * @see 删除列名为columnName列值为columnValue的数据 * @param c * Person.class * @param columnName * 列名 * @param columnValue * 列名相应的值 */ public static void deleteByColumn(Class c, String columnName, Object columnValue) { if (!getColumns(c).contains(columnName)) { System.err.println("列名‘" + columnName + "‘" + "不存在"); return; } String tableName = c.getSimpleName().toLowerCase();// person 表的名字 StringBuilder sql = new StringBuilder("delete from ").append(tableName) .append(" where ").append(columnName + "=?
"); try { PreparedStatement ps = getConnection().prepareStatement( sql.toString()); ps.setObject(1, columnValue); // ps.setObject(2,columnValue ); int result = ps.executeUpdate(); System.out.println(ps.toString().split(":")[1].trim()); if (result >= 1) { getConnection().commit(); System.out.println("删除" + result + "条记录"); } else { System.out.println("删除" + result + "条记录"); getConnection().rollback(); } } catch (Exception e) { System.err.println("delete error"); e.printStackTrace(); } } /** * @category 从实体类对象中获取主键的列名和value 利用的是filed获取 * @param c * Person.class * @param obj * 实体对象 * @return 从数据库中获取主键 然后与实体类相匹配。返回对象中的主键名和值 */ public static List<KeyValue> getEntityPrimaryKeyValueField(Class c, Object obj) { List<KeyValue> keyValues = new ArrayList<KeyValue>(); List<String> primaryKeys = getPrimaryKeys(c); Field[] fields = c.getFields();// 获取全部的属性 for (int i = 0; i < fields.length; i++) {// 全部属性为public try { for (int j = 0; j < primaryKeys.size(); j++) { if (primaryKeys.get(j) .equalsIgnoreCase(fields[i].getName())) { KeyValue kv = new KeyValue(); kv.setKey(fields[i].getName()); kv.setValue(fields[i].get(obj)); keyValues.add(kv); System.out.println(fields[i].getName() + ":" + fields[i].get(obj)); } } } catch (Exception e) { e.printStackTrace(); } } if (fields.length == 0) {// 当类的属性都是private时 // fields=c.getDeclaredFields();//获取全部的private属性 fields = c.getDeclaredFields();// //获得对象全部属性 for (int i = 0; i < fields.length; i++) { try { fields[i].setAccessible(true);// 改动訪问权限 能够訪问private for (int j = 0; j < primaryKeys.size(); j++) { if (primaryKeys.get(j).equalsIgnoreCase( fields[i].getName())) { KeyValue kv = new KeyValue(); kv.setKey(fields[i].getName()); kv.setValue(fields[i].get(obj));// 读取属性值 keyValues.add(kv); System.out.println(fields[i].getName() + ":" + fields[i].get(obj)); } } } catch (Exception e) { e.printStackTrace(); } } } return keyValues; } /** * @category 从实体类对象中获取主键的列名和value 利用的是Method get方法获取 * @param c * Person.class * @param obj * 实体对象 * @return 从数据库中获取主键 然后与实体类相匹配,返回对象中的主键名和值 */ public static List<KeyValue> getEntityPrimaryKeyValueMethod(Class c, Object obj) { List<KeyValue> keyValues = new ArrayList<KeyValue>(); List<String> primaryKeys = getPrimaryKeys(c); Field[] fields = c.getFields();// 获取全部的属性 for (int i = 0; i < fields.length; i++) {// 全部属性为public try { for (int j = 0; j < primaryKeys.size(); j++) { if (primaryKeys.get(j) .equalsIgnoreCase(fields[i].getName())) { KeyValue kv = new KeyValue(); kv.setKey(fields[i].getName()); kv.setValue(fields[i].get(obj)); keyValues.add(kv); System.out.println(fields[i].getName() + ":" + fields[i].get(obj)); } } } catch (Exception e) { e.printStackTrace(); } } if (fields.length == 0) {// 当类的属性都是private时 // fields=c.getDeclaredFields();//获取全部的private属性 fields = c.getDeclaredFields();// //获得对象全部属性 for (int i = 0; i < fields.length; i++) { try { fields[i].setAccessible(true);// 改动訪问权限 能够訪问private for (int j = 0; j < primaryKeys.size(); j++) { if (primaryKeys.get(j).equalsIgnoreCase( fields[i].getName())) { KeyValue kv = new KeyValue(); kv.setKey(fields[i].getName()); kv.setValue(fields[i].get(obj));// 读取属性值 keyValues.add(kv); System.out.println(fields[i].getName() + ":" + fields[i].get(obj)); } } } catch (Exception e) { e.printStackTrace(); } } } return keyValues; } /** * @category 从实体类对象中按顺序获取全部主键的value * @param c * Person.class * @param obj * 实体对象 * @return 从数据库中获取主键 然后与实体类相匹配,返回对象中的主键值 */ public static List<Object> getEntityPKValues(Class c, Object obj) { List<Object> keyValues = new ArrayList<Object>(); List<String> primaryKeys = getPrimaryKeys(c); Field[] fields = c.getFields();// 获取全部的属性 for (int i = 0; i < fields.length; i++) {// 全部属性为public try { for (int j = 0; j < primaryKeys.size(); j++) { if (primaryKeys.get(j) .equalsIgnoreCase(fields[i].getName())) { keyValues.add(fields[i].get(obj)); System.out.println(fields[i].getName() + ":" + fields[i].get(obj)); } } } catch (Exception e) { e.printStackTrace(); } } if (fields.length == 0) {// 当类的属性都是private时 // fields=c.getDeclaredFields();//获取全部的private属性 fields = c.getDeclaredFields();// //获得对象全部属性 for (int i = 0; i < fields.length; i++) { try { fields[i].setAccessible(true);// 改动訪问权限 能够訪问private for (int j = 0; j < primaryKeys.size(); j++) { if (primaryKeys.get(j).equalsIgnoreCase( fields[i].getName())) { keyValues.add(fields[i].get(obj)); System.out.println(fields[i].getName() + ":" + fields[i].get(obj)); } } } catch (Exception e) { e.printStackTrace(); } } } return keyValues; } /** * @see 假设有主键则运行更行,没有主键则运行插入操作 * @category 将实体类对象跟新到数据库中。假设对象中的属性与数据中不一致则更新。对象某属性为空则不更改该属性 * @param c * Person.class * @param obj * person */ public static void updateEntity(Class c, Object obj) { String tableName = c.getSimpleName().toLowerCase();// person 表的名字 List<String> primaryKeys = getPrimaryKeys(c); List<KeyValue> keyValues = getEntityPrimaryKeyValueField(c, obj); List<String> columns = getColumns(c); List<Object> values = getEntityPKValues(c, obj); Object tableDate = getEntity(c, values.toArray(new Object[] {})); // System.out.println(o); Field[] fields = c.getFields();// 获取全部的属性 System.out.println("数据库比对前:" + obj); System.out.println("数据库中数据:" + tableDate); for (int i = 0; i < fields.length; i++) {// 全部属性为public try { for (int j = 0; j < columns.size(); j++) { if (columns.get(j).equalsIgnoreCase(fields[i].getName())) { System.out.println(fields[i].getName() + ":" + fields[i].get(obj)); if (fields[i].get(obj) == null) { fields[i].set(obj, fields[i].get(tableDate)); } else if (!fields[i].get(obj).equals( fields[i].get(tableDate))) { continue; } } } } catch (Exception e) { e.printStackTrace(); } } if (fields.length == 0) {// 当类的属性都是private时 // fields=c.getDeclaredFields();//获取全部的private属性 fields = c.getDeclaredFields();// //获得对象全部属性 for (int i = 0; i < fields.length; i++) { try { fields[i].setAccessible(true);// 改动訪问权限 能够訪问private for (int j = 0; j < columns.size(); j++) { if (columns.get(j) .equalsIgnoreCase(fields[i].getName())) { System.out.println(fields[i].getName() + ":" + fields[i].get(obj)); if (fields[i].get(obj) == null) { fields[i].set(obj, fields[i].get(tableDate)); } else if (!fields[i].get(obj).equals( fields[i].get(tableDate))) { continue; } } } } catch (Exception e) { e.printStackTrace(); } } } System.out.println("数据库比对后:" + obj); insertEntity(c, obj); } public static void main(String[] args) { Class c = null; try { c = Class.forName("com.ctl.bean.Person"); // c = Class.forName("com.ctl.bean.Test"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(getAutoIncremet(c)); } }
DButils工具类能够用来获取数据库连接向数据库插入更新删除对象