zoukankan      html  css  js  c++  java
  • DButils工具类能够用来获取数据库连接向数据库插入更新删除对象2

    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.text.SimpleDateFormat;
    import java.util.*;
    import java.util.Date;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JTextField;
    
    import org.apache.log4j.Category;
    
    /**
     * @author Administrator
     * @category
     
     */
    
    public class DButils {
    
    	private static ThreadLocal<Connection> connHolder;
    	private static String driver;
    	private static String url;
    	private static String username;
    	private static String password;
    	//u6570u636Eu5E93u7C7Bu578Boracle mysql db2
    	private static String databasetype;
    	private static Connection conn;
    	private static LogUtil log;
    	private static Category logger=Category.getInstance(DButils.class);
    	static {
    		log = new LogUtil();
    		connHolder = new ThreadLocal<Connection>();
    		// if (ConfigUtils.getType("mysql.driver") == null
    		// || "".equals(ConfigUtils.getType("mysql.driver").trim())
    		// || ConfigUtils.getType("mysql.url") == null
    		// || "".equals(ConfigUtils.getType("mysql.url").trim())
    		// || ConfigUtils.getType("mysql.username") == null
    		// || "".equals(ConfigUtils.getType("mysql.username").trim())
    		// || ConfigUtils.getType("mysql.password") == null
    		// || "".equals(ConfigUtils.getType("mysql.password").trim())) {
    		// System.out.println(DButils.getCurrentDataTime() + "u8D44u6E90u6587u4EF6u672Au627Eu5230");
    		// log.WriteLine("DButils.staic{}", "u8D44u6E90u6587u4EF6u672Au627Eu5230");
    		// driver = RegisterUtil.getStringFromSystemRoot("mysql.driver");
    		// url = RegisterUtil.getStringFromSystemRoot("mysql.url");
    		// username = RegisterUtil.getStringFromSystemRoot("mysql.username");
    		// password = RegisterUtil.getStringFromSystemRoot("mysql.password");
    		// } else {
    		// System.out.println("u4ECEu8D44u6E90u6587u4EF6u83B7u53D6u914Du7F6E");
    		// log.WriteLine("DButils.staic{}", "u4ECEu8D44u6E90u6587u4EF6u83B7u53D6u914Du7F6E");
    		// driver = ConfigUtils.getType("mysql.driver");
    		// url = ConfigUtils.getType("mysql.url");
    		// username = ConfigUtils.getType("mysql.username");
    		// password = ConfigUtils.getType("mysql.password");
    		// }
    		try {
    			databasetype = ConfigUtils.getType("databasetype");
    			if (databasetype.equals("mysql")) {
    				driver = ConfigUtils.getType("mysql.driver");
    				url = ConfigUtils.getType("mysql.url");
    				username = ConfigUtils.getType("mysql.username");
    				password = ConfigUtils.getType("mysql.password");
    			} else if (databasetype.equals("oracle")) {
    				driver = ConfigUtils.getType("oracle.driver");
    				url = ConfigUtils.getType("oracle.url");
    				username = ConfigUtils.getType("oracle.username");
    				password = ConfigUtils.getType("oracle.password");
    			}
    		} catch (Exception e) {
    			log.WriteLine("DButils.staic{}", "u4ECEu8D44u6E90u6587u4EF6u4E2Du83B7u53D6u6570u636Eu5E93u53C2u6570u5931u8D25!");
    		}
    		try {
    			Class.forName(driver);
    		} catch (ClassNotFoundException e) {
    			log.WriteLine("DButils.staic{}", "Class.forName(driver) error");
    		}
    		int isInit = RegisterUtil.getIntFromSystemRoot("isInit", 0);
    		if (isInit == 1) {
    			log.WriteLine("DButils.staic{}", "isInit == 1u52A0u8F7Du6570u636Eu5E93u914Du7F6Eu7A97u4F53");
    			init("staitc{}", databasetype);
    		}
    	}
    
    	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 = value;
    		}
    
    		public KeyValue() {
    			super();
    		}
    
    		public KeyValue(Object key, Object value) {
    			super();
    			this.key = key;
    			this.value = value;
    		}
    
    		public String toString() {
    			return this.key + ":" + this.value;
    		}
    
    	}
    
    	/**
    	 * @categoryu591Au6761u4EF6u7CBEu786Eu67E5u8BE2 select * from person where id=1 and name='ctl'
    	 * @param c
    	 *            Person.class
    	 * @param columns
    	 *            u8981u5339u914Du7684u5217u540D
    	 * @param conditions
    	 *            u5217u6240u5BF9u5E94u7684u503C
    	 */
    	public static List getEntitysByColumnsAnd(Class c, String[] columns,
    			Object[] conditionsValues) {
    		String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57
    		if (!isTableExist(tableName)) {
    			System.err.println("u8868'" + tableName + "'u4E0Du5B58u5728");
    			log.WriteLine("DButils.getEntitysByColumnsAnd()", tableName
    					+ " is not isExist! u9000u51FA");
    			return null;
    		}
    		List<String> columnList = getColumns(c);
    		for (int i = 0; i < columns.length; i++) {
    			if (!columnList.contains(columns[i])) {
    				System.err.println("u5217u540D'" + columns[i] + "'u4E0Du5B58u5728");
    				log.WriteLine("DButils.getEntitysByColumnsAnd()", columns[i]
    						+ " is not isExist! u9000u51FA");
    				return null;
    			}
    		}
    		if (columns.length != conditionsValues.length) {
    			System.err.println("u5217u4E2Au6570u4E0Eu5217u5BF9u5E94u7684valueu7684u4E2Au6570u4E0Du540C");
    			log.WriteLine("DButils.getEntitysByColumnsAnd()",
    					"u5217u4E2Au6570u4E0Eu5217u5BF9u5E94u7684valueu7684u4E2Au6570u4E0Du540C! u9000u51FA");
    			return null;
    		}
    		List list = new ArrayList();
    		PreparedStatement ps = null;
    		ResultSet rs = null;
    		Field[] fields = c.getFields();// u83B7u53D6u6240u6709u7684publicu5C5Eu6027
    		if (fields.length == 0) {
    			// fields=c.getDeclaredFields();//u83B7u53D6u6240u6709u7684privateu5C5Eu6027
    			fields = c.getDeclaredFields();// u83B7u53D6get set u65B9u6CD5
    		}
    		StringBuilder sql = new StringBuilder("select * from " + tableName)
    				.append(" where");
    		for (int i = 0; i < columns.length; i++) {
    			if (i < columns.length - 1) {
    				sql.append(" " + columns[i]).append("=? and");
    			} else {
    				sql.append(" " + columns[i]).append("=?");
    			}
    		}
    		log.WriteLine("DButils.getEntitysByColumnsAnd()", "sql:"
    				+ sql.toString());
    		try {
    			if (!isTableExist(tableName)) {
    				System.err.println("u8868u4E0Du5B58u5728");
    				return list;
    			}
    			ps = (PreparedStatement) getConnection().prepareStatement(
    					sql.toString());
    			for (int i = 0; i < columns.length; i++) {
    				ps.setObject(i + 1, conditionsValues[i]);
    			}
    			rs = ps.executeQuery();
    			log.WriteLine("DButils.getEntitysByColumnsAnd()", "sql:"
    					+ ps.toString().split(":")[1]);
    			System.out.println("
    " + ps.toString().split(":")[1]);
    			log.WriteLine("DButils.getEntitysByColumnsAnd()", "sql:"
    					+ 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) {
    			log.WriteLine("DButils.getEntitysByColumnsAnd()",
    					"getEntitysByColumnsAnd error");
    		} finally {
    			rs = null;
    			ps = null;
    		}
    		return list;
    
    	}
    
    	/**
    	 * @category u591Au6761u4EF6u6A21u7CCAu67E5u8BE2
    	 * @param c
    	 * @param columns
    	 * @param conditions
    	 */
    	public static List getEntitysByColumnsOr(Class c, String[] columns,
    			Object[] conditionsValues) {
    		String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57
    		if (!isTableExist(tableName)) {
    			System.err.println("u8868'" + tableName + "'u4E0Du5B58u5728");
    			log.WriteLine("DButils.getEntitysByColumnsOr()", tableName
    					+ " is not isExist! u9000u51FA");
    			return null;
    		}
    		List<String> columnList = getColumns(c);
    		for (int i = 0; i < columns.length; i++) {
    			if (!columnList.contains(columns[i])) {
    				System.err.println("u5217u540D'" + columns[i] + "'u4E0Du5B58u5728");
    				log.WriteLine("DButils.getEntitysByColumnsOr()", columns[i]
    						+ " is not isExist! u9000u51FA");
    				return null;
    			}
    		}
    		if (columns.length != conditionsValues.length) {
    			System.err.println("u5217u4E2Au6570u4E0Eu5217u5BF9u5E94u7684valueu7684u4E2Au6570u4E0Du540C");
    			log.WriteLine("DButils.getEntitysByColumnsOr()",
    					"u5217u4E2Au6570u4E0Eu5217u5BF9u5E94u7684valueu7684u4E2Au6570u4E0Du540C! u9000u51FA");
    			return null;
    		}
    		List list = new ArrayList();
    		PreparedStatement ps = null;
    		ResultSet rs = null;
    		Field[] fields = c.getFields();// u83B7u53D6u6240u6709u7684publicu5C5Eu6027
    		if (fields.length == 0) {
    			// fields=c.getDeclaredFields();//u83B7u53D6u6240u6709u7684privateu5C5Eu6027
    			fields = c.getDeclaredFields();// u83B7u53D6get set u65B9u6CD5
    		}
    		StringBuilder sql = new StringBuilder("select * from " + tableName)
    				.append(" where");
    		for (int i = 0; i < columns.length; i++) {
    			if (i < columns.length - 1) {
    				sql.append(" " + columns[i]).append("=? or");
    			} else {
    				sql.append(" " + columns[i]).append("=?");
    			}
    		}
    		log.WriteLine("DButils.getEntitysByColumnsOr()", "sql:"
    				+ sql.toString());
    		try {
    			if (!isTableExist(tableName)) {
    				System.err.println("u8868u4E0Du5B58u5728");
    				return list;
    			}
    			ps = (PreparedStatement) getConnection().prepareStatement(
    					sql.toString());
    			for (int i = 0; i < columns.length; i++) {
    				ps.setObject(i + 1, conditionsValues[i]);
    			}
    			rs = ps.executeQuery();
    			log.WriteLine("DButils.getEntitysByColumnsOr()", "sql:"
    					+ ps.toString().split(":")[1]);
    			System.out.println("
    " + 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) {
    			log.WriteLine("DButils.getEntitysByColumnsOr()",
    					"getEntitysByColumnsOr error");
    		} finally {
    			rs = null;
    			ps = null;
    		}
    		return list;
    
    	}
    
    	/**
    	 * @author Administrator
    	 * @category start mysql server
    	 */
    	public static void startMySqlServer() {
    		try {
    			Runtime.getRuntime().exec("net start mysql");
    			log.WriteLine("DButils.startMySqlServer()", "");
    		} catch (IOException e) {
    			log.WriteLine("DButils.startMySqlServer()",
    					"mysql server start error");
    		}
    	}
    
    	/**
    	 * @categoryu521Du59CBu5316u6570u636Eu5E93
    	 * @param string
    	 */
    	public static void init(String string,String databasetype) {
    		if(databasetype.equals("mysql")){
    			startMySqlServer();
    		}else if(databasetype.equals("oracle")){
    			startOracleServer();
    		}
    		new InitJFrame(string,databasetype);
    	}
    
    	private static void startOracleServer() {
    		try {
    			Runtime.getRuntime().exec(
    					new String[] { "net start OracleOraDb11g_home1TNSListener",
    							" net start OracleServiceORCL" });
    			log.WriteLine("DButils.startOracleServer", "");
    		} catch (IOException e) {
    			log.WriteLine("DButils.startOracleServer",
    					"oracle server start error");
    		}
    	}
    
    	/**
    	 * @author Administrator
    	 * @category stop mysql server
    	 */
    	public static void stopMySqlServer() {
    		try {
    			Runtime.getRuntime().exec("net stop mysql");
    		} catch (IOException e) {
    			log.WriteLine("DButils.stopMySqlServer()",
    					"mysql server stop error");
    			System.err.println("mysql server stop error");
    		}
    	}
    
    	/**
    	 * @category u662Fu5426u6267u884Cinitu65B9u6CD5 u82E5isExcuteInitu4E3Atrueu8FD9u6267u884C u5426u5219u4E0Du6267u884C
    	 * @param isExcuteInit
    	 */
    	public static void isExecuteInit(boolean isExcuteInit) {
    		if (isExcuteInit) {
    			RegisterUtil.putIntSystemRoot("isInit", 1);
    		} else {
    			RegisterUtil.putIntSystemRoot("isInit", 0);
    		}
    	}
    
    	/**
    	 * @category u6570u636Eu5E93u662Fu5426u81EAu52A8u63D0u4EA4
    	 * @param autoCommit
    	 */
    	public static void setAutoCommit(boolean autoCommit) {
    		if (autoCommit) {
    			RegisterUtil.putIntSystemRoot("autoCommit", 1);// 1u662Fu81EAu52A8u63D0u4EA4
    		} else {
    			RegisterUtil.putIntSystemRoot("autoCommit", 0);// 0u662Fu9700u8981u6267u884Ccommitt
    		}
    	}
    
    	/**
    	 * @category get isAutoCommit
    	 * @return boolean
    	 */
    	public static boolean getAutoCommit() {
    		int flag = RegisterUtil.getIntFromSystemRoot("autoCommit", 1);
    		return flag == 1 ? true : false;
    	}
    
    	/**
    	 * @category u5982u679CautoCommit=true u5219u4E0Du505Au64CDu4F5Cu5426u5219u6267u884Cconn.commit()
    	 */
    	public static void commit() {
    		int isCommit = RegisterUtil.getIntFromSystemRoot("autoCommit", 1);
    		if (isCommit != 1) {
    			try {
    				conn.commit();
    			} catch (SQLException e) {
    				log.WriteLine("DButils.commit()", "commit error");
    				System.out.println("db commit false");
    				exceptionPrint(e);
    			}
    
    		}
    	}
    
    	/**
    	 * 
    	 * @return Connection
    	 * @throws SQLException
    	 * @throws ClassNotFoundException
    	 */
    
    	public static Connection getConnection() {
    		conn = connHolder.get();
    		try {
    			if (conn == null || conn.isClosed()) {
    				conn = DriverManager.getConnection(url, username, password);
    				//conn.setAutoCommit(getAutoCommit());
    				conn.setAutoCommit(false);
    				connHolder.set(conn);
    			}
    		} catch (Exception e) {
    			log.WriteLine("DButils.getConnection{}", "getConnection error");
    			logger.error(e.getMessage());
    			init("getConnection",databasetype);
    			exceptionPrint(e);
    		}
    		return conn;
    	}
    
    	/**
    	 * @category u6253u5370u9519u8BEF
    	 * @param e
    	 */
    	public static void exceptionPrint(Exception e) {
    		StackTraceElement[] errors = e.getStackTrace();
    		System.out.println();
    		for (int i = 0; i < errors.length; i++) {
    			if (DButils.class.getName().equals(errors[i].getClassName())) {
    				System.out.print("Exception: " + getCurrentDataTime() + "  "
    						+ errors[i].getClassName() + "."
    						+ errors[i].getMethodName() + "() line:"
    						+ errors[i].getLineNumber() + "
    ");
    			}
    		}
    		e.printStackTrace();
    		System.out.println();
    	}
    
    	/**
    	 * @category u6839u636Esqlu5F97u5230u8BB0u5F55u603Bu6570
    	 * @param sql
    	 * @return int u5982u679Cu8FD4u56DE-1u4EE3u8868u51FAu9519
    	 */
    	public static int getCount(String sql) {
    		try {
    			ResultSet rs = getConnection().createStatement().executeQuery(sql);
    			int count = -1;
    			if (rs.next()) {
    				count = rs.getInt(1);
    			}
    			rs.close();
    			return count;
    		} catch (Exception e) {
    			log.WriteLine("DButils.getCount{}", "getCount error sql:" + sql);
    			exceptionPrint(e);
    		}
    		return -1;
    	}
    
    	/**
    	 * @see u83B7u53D6u67D0u5F20u8868u7684u603Bu8BB0u5F55u6570
    	 * @param c
    	 *            Person.class
    	 * @return -1 u51FAu9519 >=0 right
    	 */
    	public static int getCount(Class c) {
    		String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57
    		if (!isTableExist(tableName)) {
    			System.err.println("u8868'" + tableName + "'u4E0Du5B58u5728");
    			return -1;
    		}
    		int count = -1;
    		try {
    			ResultSet rs = getConnection().prepareStatement(
    					"select count(" + getColumns(c).get(0) + ") from "
    							+ tableName).executeQuery();
    			if (rs.next()) {
    				count = rs.getInt(1);
    			}
    			rs.close();
    			return count;
    		} catch (Exception e) {
    			log.WriteLine("DButils.getCount{}", "getCount error");
    			e.printStackTrace();
    		}
    		return count;
    	}
    
    	/**
    	 * @category u5F39u51FAu6570u636Eu5E93u914Du7F6Eu7A97u53E3
    	 */
    	public static void init() {
    		init(null,databasetype);
    	}
    
    	/**
    	 * @category close Connection
    	 * @throws SQLException
    	 */
    	public static void close() throws SQLException {
    		conn.close();
    		conn = null;
    		connHolder.set(null);
    	}
    
    	public static int createTable(Class c) {
    		String tableName = c.getSimpleName().toLowerCase();// person
    		return 0;
    	}
    
    	/**
    	 * 
    	 * @param c
    	 *            u53C2u6570u4F8Bu5982Person.class
    	 * @param obj
    	 *            u53C2u6570u4F8Bu5982 person obju4E3Au67D0u4E00u5B9Eu4F8Bu5BF9u8C61 // Person person=new Person();
    	 * @category u8BE5u65B9u6CD5u7528u4E8Eu5411u6570u636Eu5E93u4E2Du63D2u5165u6761u6570u636E u63D2u5165u7684u5BF9u8C61u662Fu4E00u4E2Au5B9Eu4F53u7C7Bu7684u5BF9u8C61
    	 */
    	public static void insertEntity(Class c, Object obj) {
    		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(")"); log.WriteLine("DButils.insertEntity()", "insertEntity sql:" + 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(); System.out.println(" sql:" + ps.toString().split(":")[1].trim()); log.WriteLine("DButils.insertEntity()", "insertEntity sql:" + ps.toString().split(":")[1].trim() + " Entity:" + obj); ps.close(); ps = null; } catch (Exception e1) { e1.printStackTrace(); } } /** * @category u6839u636Eu4F20u5165u7684u4E3Bu952Eu503Cu8FD4u56DEu4E00u4E2Au5B9Eu4F53u5BF9u8C61 * @param c * for example Person.class * @param primaryKeys * primaryKeysu4E3Au4E3Bu952E,u53C2u6570u987Au5E8Fu548Cu8868u4E2Du4FDDu6301u4E00u81F4 u5982u679CiduFF0C name u4E3Au4E3Bu952E u7C7Bu540Du4E3APerson u5219 * 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;// u8981u8FD4u56DEu7684u5BF9u8C61 String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57 List primaryKeyNameList = new ArrayList();// u5B58u653Eu4ECEu8868u4E2Du83B7u53D6u7684u4E3Bu952E Field[] fields = c.getFields();// u83B7u53D6u6240u6709u7684u5C5Eu6027 Method[] methods = null; if (fields.length == 0) {// u5F53u7C7Bu7684u5C5Eu6027u90FDu662Fprivateu65F6 // fields=c.getDeclaredFields();//u83B7u53D6u6240u6709u7684privateu5C5Eu6027 methods = c.getDeclaredMethods();// u83B7u53D6get set u65B9u6CD5 } StringBuilder sql = new StringBuilder("select * from " + tableName + " where "); try { obj = c.newInstance(); if (!isTableExist(tableName)) { System.err.println("u8868u4E0Du5B58u5728"); return obj; } dmd = getConnection().getMetaData(); rs = dmd.getPrimaryKeys(null, null, tableName); while (rs.next()) {// u83B7u53D6u6240u6709u7684u4E3Bu952E sql.append(rs.getObject(4) + "=?"); sql.append(" and "); primaryKeyNameList.add(rs.getObject(4));// u5C06u4ECEu8868u4E2Du83B7u53D6u7684 u4E3Bu952Eu5B57u6BB5u5B58u5230 listu4E2DuFF0C // u4E3Bu952Eu4F4Du4E8Eu8868u4E2Du7B2Cu51E0u5217=rs.getString(5) } sql.delete(sql.length() - 4, sql.length()); if (!sql.toString().contains("where")) { System.err.println("u6CA1u6709u627Eu5230u4E3Bu952E"); 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) {// u5982u679Cu7C7B u7684u5C5Eu6027u4E3Apublic for (int k = 0; k < fields.length; k++) { fields[k].set(obj, rs.getObject(k + 1)); } } else {// u5982u679Cu7C7B u7684u5C5Eu6027u4E3Aprivate 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(); log.WriteLine("DButils.getEntity()", "getEntity error talbename:" + tableName); } return obj; } /** * * @param tableName * u6807u7684u540Du5B57 * @category u8868u4E0Du5B58u5728 1u8868u5B58u5728 * @return 0u8868u4E0Du5B58u5728 >=1u8868u5B58u5728 */ 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("u8868 u4E0Du5B58u5728 table not exist"); log.WriteLine("DButils.isTableExist()", "u8868u4E0Du5B58u5728"); return false; } } /** * * @category u83B7u53D6u67D0u4E2Au8868u4E2Du6240u6709u7684u5217u540D * @param c * Person.class (u7C7Bu540Du4E0Eu8868u540Du4E00u81F4) * @return List */ public static List<String> getColumns(Class c) { List<String> list = new ArrayList<String>(); String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57 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));// u9632u6B62u4E0Du540Cu6570u636Eu5E93u4E2Du6709u76F8u540Cu7684u8868u540D } } rs.close(); } catch (Exception e) { log.WriteLine("DButils.getColumns()", "getColumns error "); e.printStackTrace(); } return list; } /** * @category u8FD4u56DEu5F53u524Du65F6u95F4 String * @return String now system date yyyy/MM/dd hh:mm:ss */ public static String getCurrentDataTime(String datetimeFormat) { Date date = new Date(); SimpleDateFormat sdf = null; if (datetimeFormat == null || "".equals(datetimeFormat)) { sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm:ss"); } sdf.format(date); return sdf.format(date); } /** * @category u8FD4u56DEu5F53u524Du65F6u95F4 String * @return String now system date */ public static String getCurrentDataTime() { return getCurrentDataTime(null); } /** * @category u8FD4u56DEu6570u636Eu5E93u7684u540Du5B57 * @param Person * .class * @return database name */ public static String getDatabaseName(Class c) { String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57 try { ResultSet rs = getConnection().getMetaData().getPrimaryKeys(null, null, tableName); String result = null; if (rs.next()) { System.out.println("database:" + rs.getString(1)); result = rs.getString(1); rs.close(); rs = null; return result; } } catch (Exception e) { System.err.println("u83B7u53D6u6570u636Eu5E93u540Du5931u8D25"); log.WriteLine("DButils.getDatabaseName()", "getDatabaseName error"); exceptionPrint(e); } return null; } /** * @category u8FD4u56DE int auto_incrementu7684u4E0Bu4E00u4E2Au81EAu589Eu503C * @param c * Personu3002class * @return int u4E0Bu4E00u4E2Au81EAu589Eu503C u5982u679Cu6CA1u6709u5219u8FD4u56DEnull */ public static int getAutoIncremet(Class c) { String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57 if (!isTableExist(tableName)) { System.err.println("u8868'" + tableName + "'u4E0Du5B58u5728"); return -1; } int count = -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()) { count = rs.getInt(1); } rs.close(); } catch (Exception e) { log.WriteLine("DButils.getAutoIncremet()", "getAutoIncremet error"); e.printStackTrace(); } return count; } /** * @category u67E5u627Eu67D0u4E00u5217u7684u6240u6709u503C * @param c * Person.class * @param columnName * u8981u67E5u627Eu7684u67D0u4E00u5217u7684u5217u540D * @return List<String> u8FD4u56DEu67D0u4E00u5217u7684u6240u6709u503C */ public static List<String> getColumnData(Class c, String columnName) { if (!getColumns(c).contains(columnName)) { System.err.println("u5217u540D'" + columnName + "'u4E0Du5B58u5728"); return null; } List<String> list = new ArrayList<String>(); String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57 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)); } rs.close(); } catch (Exception e) { log.WriteLine("DButils.getColumnData()", "getColumnData error"); exceptionPrint(e); } return list; } /** * @category u6839u636Eu6761u4EF6u67E5u8BE2 u8FD4u56DEwhere columnName=value * @param c * Person.class u4E14Person u6240u6709u7684u5C5Eu6027u5FC5u987Bu5168u4E3Au4E3Apublicu7C7Bu578Bu6216u8005u5168u90E8u4E3Aprivate * @param columnName * u8868u4E2Du7684u67D0u5B57u6BB5 * @param value * columnNameu5BF9u5E94u7684u503C * @return List */ public static List getEntitys(Class c, String columnName, Object value) { if (!getColumns(c).contains(columnName)) { System.err.println("u5217u540D'" + columnName + "'u4E0Du5B58u5728"); log.WriteLine("DButils.getEntitys()", "u5217u540Du4E0Du5B58u5728 u63A8u51FA"); return null; } List list = new ArrayList(); PreparedStatement ps = null; ResultSet rs = null; String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57 Field[] fields = c.getFields();// u83B7u53D6u6240u6709u7684publicu5C5Eu6027 Method[] methods = null; if (fields.length == 0) { fields = c.getDeclaredFields();// u83B7u53D6u6240u6709u7684privateu5C5Eu6027 methods = c.getDeclaredMethods();// u83B7u53D6get set u65B9u6CD5 } StringBuilder sql = new StringBuilder("select * from " + tableName + " where " + columnName + "=?"); try { if (!isTableExist(tableName)) { System.err.println("u8868u4E0Du5B58u5728"); return list; } ps = (PreparedStatement) getConnection().prepareStatement( sql.toString()); ps.setObject(1, value); rs = ps.executeQuery(); System.out.println(" " + ps.toString().split(":")[1]); Object obj = null; while (rs.next()) { obj = c.newInstance(); if (fields.length > 0) {// u5982u679Cu7C7B u7684u5C5Eu6027u4E3Apublic for (int k = 0; k < fields.length; k++) { fields[k].setAccessible(true); fields[k].set(obj, rs.getObject(k + 1)); } } else {// u5982u679Cu7C7B u7684u5C5Eu6027u4E3Aprivate 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) { log.WriteLine("DButils.getEntitys()", "getEntitys error"); e.printStackTrace(); } finally { rs = null; ps = null; } return list; } /** * @see u83B7u53D6u6240u6709u7684u6570u636E * @param c * Person.class * @return Listu6240u6709u7684u6570u636E */ public static List getAllEntitys(Class c) { String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57 if (!isTableExist(tableName)) { System.err.println("u8868'" + tableName + "'u4E0Du5B58u5728"); log.WriteLine("DButils.getAllEntitys()", tableName + " is not isExist! u9000u51FA"); return null; } List list = new ArrayList(); PreparedStatement ps = null; ResultSet rs = null; Field[] fields = c.getFields();// u83B7u53D6u6240u6709u7684publicu5C5Eu6027 if (fields.length == 0) { // fields=c.getDeclaredFields();//u83B7u53D6u6240u6709u7684privateu5C5Eu6027 fields = c.getDeclaredFields();// u83B7u53D6get set u65B9u6CD5 } StringBuilder sql = new StringBuilder("select * from " + tableName); try { if (!isTableExist(tableName)) { System.err.println("u8868u4E0Du5B58u5728"); return list; } ps = (PreparedStatement) getConnection().prepareStatement( sql.toString()); rs = ps.executeQuery(); System.out.println(" " + 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) { log.WriteLine("DButils.getAllEntitys()", "getAllEntitys error"); } finally { rs = null; ps = null; } return list; } /** * @see u83B7u53D6u6240u6709u7684u6570u636E * @param c * Person.class * @param columns * u8981u6392u5E8Fu7684columns u5982 IduFF0Cname u6216u5355u72ECu4E00u4E2Aname * @param ascOrDesc * ascu6216desc * @return Listu6240u6709u7684u6570u636E */ public static List getAllEntitysOrderByColumns(Class c, String[] columns, String ascOrDesc) { String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57 if (!isTableExist(tableName)) { System.err.println("u8868'" + tableName + "'u4E0Du5B58u5728"); log.WriteLine("DButils.getAllEntitysOrderByColumns()", tableName + " is not isExist! u9000u51FA"); return null; } List<String> columnList = getColumns(c); for (int i = 0; i < columns.length; i++) { if (!columnList.contains(columns[i])) { System.err.println("u5217u540D'" + columns[i] + "'u4E0Du5B58u5728"); log.WriteLine("DButils.getAllEntitysOrderByColumns()", columns[i] + " is not isExist! u9000u51FA"); return null; } } if (!ascOrDesc.equalsIgnoreCase("asc") && ascOrDesc.equalsIgnoreCase("desc")) { log.WriteLine("DButils.getAllEntitysOrderByColumns()", "u6392u5E8Fu5173u952Eu5B57u9519u8BEF"); return null; } List list = new ArrayList(); PreparedStatement ps = null; ResultSet rs = null; Field[] fields = c.getFields();// u83B7u53D6u6240u6709u7684publicu5C5Eu6027 if (fields.length == 0) { // fields=c.getDeclaredFields();//u83B7u53D6u6240u6709u7684privateu5C5Eu6027 fields = c.getDeclaredFields();// u83B7u53D6get set u65B9u6CD5 } StringBuilder sql = new StringBuilder("select * from " + tableName + " order by "); for (int i = 0; i < columns.length; i++) { if (i < columns.length - 1) { sql.append("" + columns[i] + ","); } else { sql.append("" + columns[i] + " " + ascOrDesc); } } log.WriteLine("DButils.getAllEntitysOrderByColumn()", "sql:" + sql.toString()); try { if (!isTableExist(tableName)) { System.err.println("u8868u4E0Du5B58u5728"); return list; } ps = (PreparedStatement) getConnection().prepareStatement( sql.toString()); rs = ps.executeQuery(); System.out.println(" " + 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) { log.WriteLine("DButils.getAllEntitysOrderByColumn()", "getAllEntitysOrderByColumn error"); } finally { rs = null; ps = null; } return list; } /** * @see u83B7u53D6u6570u636Eu4E2Du7684u67D0u51E0u6761u8BB0u5F55 * @param c * Person.class * @param fromNumber * u4ECEu6570u636Eu5E93u7684u7B2Cu51E0u6761u5F00u59CBuFF080uFF0C1uFF0C2uFF0C3uFF09 * @param number * u4ECEfromNumberu5F00u59CBu83B7u53D6u591Au5C11u884C * @return List */ public static List getEntitysLimit(Class c, int fromNumber, int number) { String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57 if (!isTableExist(tableName)) { System.err.println("u8868'" + tableName + "'u4E0Du5B58u5728"); return null; } List list = new ArrayList(); PreparedStatement ps = null; ResultSet rs = null; Field[] fields = c.getFields();// u83B7u53D6u6240u6709u7684publicu5C5Eu6027 if (fields.length == 0) { // fields=c.getDeclaredFields();//u83B7u53D6u6240u6709u7684privateu5C5Eu6027 fields = c.getDeclaredFields();// u83B7u53D6get set u65B9u6CD5 } StringBuilder sql = new StringBuilder("select * from " + tableName) .append(" limit ?

    ,?"); try { if (!isTableExist(tableName)) { System.err.println("u8868u4E0Du5B58u5728"); return list; } ps = (PreparedStatement) getConnection().prepareStatement( sql.toString()); ps.setInt(1, fromNumber); ps.setInt(2, number); rs = ps.executeQuery(); System.out.println(" " + ps.toString().split(":")[1]); log.WriteLine("DButils.getEntitysLimit()", 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) { log.WriteLine("DButils.getEntitysLimit()", "getEntitysLimit error"); exceptionPrint(e); } finally { rs = null; ps = null; } return list; } /** * @category u8FD4u56DEu8868u4E2Du6240u6709u7684u4E3Bu952E * @param c * Person.class * @return list */ public static List<String> getPrimaryKeys(Class c) { String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57 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)); } rs.close(); } catch (Exception e) { log.WriteLine("DButils.getPrimaryKeys()", "getPrimaryKeys error"); exceptionPrint(e); } return list; } /** * @category u6839u636Eu4E3Bu952Eu5220u9664u6570u636E * @param c * Person.class * @param primaryKey * u6309u8868u4E2Du4E3Bu952Eu5220u9664 u5982u679Cu4E3Bu952Eu4E3Aidu3002name * u5219deleteByPrimaryKey(Person.class,1,"ctl"); */ public static void deleteByPrimaryKey(Class c, Object... primaryKey) { String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57 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(); System.out.println(ps.toString().split(":")[1].trim()); ps.close(); } catch (Exception e) { log.WriteLine("DButils.deleteByPrimaryKey()", "deleteByPrimaryKey error"); ps = null; exceptionPrint(e); } } /** * @see u5220u9664u5217u540Du4E3AcolumnNameu5217u503Cu4E3AcolumnValueu7684u6570u636E * @param c * Person.class * @param columnName * u5217u540D * @param columnValue * u5217u540Du5BF9u5E94u7684u503C */ public static void deleteByColumn(Class c, String columnName, Object columnValue) { if (!getColumns(c).contains(columnName)) { System.err.println("u5217u540D'" + columnName + "'" + "u4E0Du5B58u5728"); return; } String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57 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 ); ps.executeUpdate(); System.out.println(ps.toString().split(":")[1].trim()); ps.close(); } catch (Exception e) { log.WriteLine("DButils.deleteByColumn()", "deleteByColumn error"); System.err.println("delete error"); e.printStackTrace(); } } /** * @category u4ECEu5B9Eu4F53u7C7Bu5BF9u8C61u4E2Du83B7u53D6u4E3Bu952Eu7684u5217u540Du548Cvalue u5229u7528u7684u662Ffiledu83B7u53D6 * @param c * Person.class * @param obj * u5B9Eu4F53u5BF9u8C61 * @return u4ECEu6570u636Eu5E93u4E2Du83B7u53D6u4E3Bu952E u7136u540Eu4E0Eu5B9Eu4F53u7C7Bu76F8u5339u914DuFF0Cu8FD4u56DEu5BF9u8C61u4E2Du7684u4E3Bu952Eu540Du548Cu503C */ public static List<KeyValue> getEntityPrimaryKeyValueField(Class c, Object obj) { List<KeyValue> keyValues = new ArrayList<KeyValue>(); List<String> primaryKeys = getPrimaryKeys(c); Field[] fields = c.getFields();// u83B7u53D6u6240u6709u7684u5C5Eu6027 for (int i = 0; i < fields.length; i++) {// u6240u6709u5C5Eu6027u4E3Apublic 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) { log.WriteLine("DButils.getEntityPrimaryKeyValueField()", "getEntityPrimaryKeyValueField error"); exceptionPrint(e); } } if (fields.length == 0) {// u5F53u7C7Bu7684u5C5Eu6027u90FDu662Fprivateu65F6 // fields=c.getDeclaredFields();//u83B7u53D6u6240u6709u7684privateu5C5Eu6027 fields = c.getDeclaredFields();// //u83B7u5F97u5BF9u8C61u6240u6709u5C5Eu6027 for (int i = 0; i < fields.length; i++) { try { fields[i].setAccessible(true);// u4FEEu6539u8BBFu95EEu6743u9650 u53EFu4EE5u8BBFu95EEprivate 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));// u8BFBu53D6u5C5Eu6027u503C keyValues.add(kv); // System.out.println(fields[i].getName() + ":" // + fields[i].get(obj)); } } } catch (Exception e) { log.WriteLine("DButils.getEntityPrimaryKeyValueField()", "getEntityPrimaryKeyValueField error"); exceptionPrint(e); } } } return keyValues; } /** * @category u4ECEu5B9Eu4F53u7C7Bu5BF9u8C61u4E2Du83B7u53D6u4E3Bu952Eu7684u5217u540Du548Cvalue u5229u7528u7684u662FMethod getu65B9u6CD5u83B7u53D6 * @param c * Person.class * @param obj * u5B9Eu4F53u5BF9u8C61 * @return u4ECEu6570u636Eu5E93u4E2Du83B7u53D6u4E3Bu952E u7136u540Eu4E0Eu5B9Eu4F53u7C7Bu76F8u5339u914DuFF0Cu8FD4u56DEu5BF9u8C61u4E2Du7684u4E3Bu952Eu540Du548Cu503C */ public static List<KeyValue> getEntityPrimaryKeyValueMethod(Class c, Object obj) { List<KeyValue> keyValues = new ArrayList<KeyValue>(); List<String> primaryKeys = getPrimaryKeys(c); Field[] fields = c.getFields();// u83B7u53D6u6240u6709u7684u5C5Eu6027 for (int i = 0; i < fields.length; i++) {// u6240u6709u5C5Eu6027u4E3Apublic 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) {// u5F53u7C7Bu7684u5C5Eu6027u90FDu662Fprivateu65F6 // fields=c.getDeclaredFields();//u83B7u53D6u6240u6709u7684privateu5C5Eu6027 fields = c.getDeclaredFields();// //u83B7u5F97u5BF9u8C61u6240u6709u5C5Eu6027 for (int i = 0; i < fields.length; i++) { try { fields[i].setAccessible(true);// u4FEEu6539u8BBFu95EEu6743u9650 u53EFu4EE5u8BBFu95EEprivate 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));// u8BFBu53D6u5C5Eu6027u503C keyValues.add(kv); System.out.println(fields[i].getName() + ":" + fields[i].get(obj)); } } } catch (Exception e) { e.printStackTrace(); } } } return keyValues; } /** * @category u4ECEu5B9Eu4F53u7C7Bu5BF9u8C61u4E2Du6309u987Au5E8Fu83B7u53D6u6240u6709u4E3Bu952Eu7684value * @param c * Person.class * @param obj * u5B9Eu4F53u5BF9u8C61 * @return u4ECEu6570u636Eu5E93u4E2Du83B7u53D6u4E3Bu952E u7136u540Eu4E0Eu5B9Eu4F53u7C7Bu76F8u5339u914DuFF0Cu8FD4u56DEu5BF9u8C61u4E2Du7684u4E3Bu952Eu503C */ public static List<Object> getEntityPKValues(Class c, Object obj) { List<Object> keyValues = new ArrayList<Object>(); List<String> primaryKeys = getPrimaryKeys(c); Field[] fields = c.getFields();// u83B7u53D6u6240u6709u7684u5C5Eu6027 for (int i = 0; i < fields.length; i++) {// u6240u6709u5C5Eu6027u4E3Apublic 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) { log.WriteLine("DButils.getEntityPKValues()", "getEntityPKValues error"); exceptionPrint(e); } } if (fields.length == 0) {// u5F53u7C7Bu7684u5C5Eu6027u90FDu662Fprivateu65F6 // fields=c.getDeclaredFields();//u83B7u53D6u6240u6709u7684privateu5C5Eu6027 fields = c.getDeclaredFields();// //u83B7u5F97u5BF9u8C61u6240u6709u5C5Eu6027 for (int i = 0; i < fields.length; i++) { try { fields[i].setAccessible(true);// u4FEEu6539u8BBFu95EEu6743u9650 u53EFu4EE5u8BBFu95EEprivate 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) { log.WriteLine("DButils.getEntityPKValues()", "getEntityPKValues error"); exceptionPrint(e); } } } return keyValues; } /** * @see u5982u679Cu6709u4E3Bu952Eu5219u6267u884Cu66F4u884CuFF0Cu6CA1u6709u4E3Bu952Eu5219u6267u884Cu63D2u5165u64CDu4F5C * @category u5C06u5B9Eu4F53u7C7Bu5BF9u8C61u8DDFu65B0u5230u6570u636Eu5E93u4E2DuFF0Cu5982u679Cu5BF9u8C61u4E2Du7684u5C5Eu6027u4E0Eu6570u636Eu4E2Du4E0Du4E00u81F4u5219u66F4u65B0uFF0Cu5BF9u8C61u67D0u5C5Eu6027u4E3Au7A7Au5219u4E0Du66F4u6539u8BE5u5C5Eu6027 * @param c * Person.class * @param obj * person */ public static void updateEntity(Class c, Object obj) { String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57 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();// u83B7u53D6u6240u6709u7684u5C5Eu6027 System.out.println("u6570u636Eu5E93u6BD4u5BF9u524D:" + obj); System.out.println("u6570u636Eu5E93u4E2Du6570u636E:" + tableDate); for (int i = 0; i < fields.length; i++) {// u6240u6709u5C5Eu6027u4E3Apublic 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) { log.WriteLine("DButils.updateEntity()", "updateEntity error"); exceptionPrint(e); } } if (fields.length == 0) {// u5F53u7C7Bu7684u5C5Eu6027u90FDu662Fprivateu65F6 // fields=c.getDeclaredFields();//u83B7u53D6u6240u6709u7684privateu5C5Eu6027 fields = c.getDeclaredFields();// //u83B7u5F97u5BF9u8C61u6240u6709u5C5Eu6027 for (int i = 0; i < fields.length; i++) { try { fields[i].setAccessible(true);// u4FEEu6539u8BBFu95EEu6743u9650 u53EFu4EE5u8BBFu95EEprivate 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) { log.WriteLine("DButils.updateEntity()", "updateEntity error"); } } } System.out.println("u6570u636Eu5E93u6BD4u5BF9u540E:" + obj); insertEntity(c, obj); } static class InitJFrame { private InitJFrame(String databasetype) { this(null,databasetype); } private InitJFrame(final String jfTitle,String databasetype) { initJFrame_mysql(jfTitle, databasetype); initJFrame_oracle(jfTitle, databasetype); } private void initJFrame_oracle(final String jfTitle, String databasetype) { if(databasetype.equals("oracle")){ Thread t_oracle = new Thread() { public void run() { String title; Font fontGlobal = new Font("u6977u4F53", 11, 10); if (jfTitle != null && !"".equals(jfTitle) && !"null".equals(jfTitle)) { title = "oracleu6570u636Eu5E93u521Du59CBu5316:" + jfTitle; } else { title = "oracleu6570u636Eu5E93u521Du59CBu5316"; } JFrame jf = new JFrame(title); jf.setVisible(true); jf.setBounds(600, 260, 266, 166); // jf.setBounds(600, 260, 266, 366); jf.setVisible(true); // jf.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); 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 jls2 = new JLabel("u4E3Bu673Au540D/ip:"); jls2.setBounds(0, 5, 50, 45); jpanel.add(jls2); jls2.setFont(fontGlobal); 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("u7AEFu53E3:"); 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("1521"); JLabel jls4 = new JLabel("u7528u6237u540D:"); 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("system"); JLabel jls5 = new JLabel("u5BC6u7801:"); 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("system"); final JLabel jls6 = new JLabel("SID:"); jls6.setBounds(26, 65, 50, 45); jpanel.add(jls6); jls6.setFont(fontGlobal); final JTextField jtfip11 = new JTextField(18); jtfip11.setBounds(50, 77, 58, 20); jpanel.add(jtfip11); jtfip11.setText("fastatm"); // JLabel jls51 = new JLabel("u7F16u7801:"); // jls51.setBounds(123, 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("u521Du59CBu5316DButilsu5DE5u5177u7C7B"); linkBtn.setBounds(56, 111, 150, 20); jpanel.add(linkBtn); linkBtn.setMargin(new Insets(0, 0, 0, 0));// u8FD9u6837u8BBEu7F6Ebuttonu4E2Du7684u5B57u4F53u4E0Ebuttonu65E0u4E0Au4E0Bu8FB9u8DDD linkBtn.setFont(fontGlobal); MouseAdapter linkServerListener = new MouseAdapter() { public void mouseClicked(MouseEvent e) { String ip = jtfip.getText().trim(); int port = Integer.parseInt(jtfport.getText() .trim()); username = jtfip1.getText().trim(); password = jtfport1.getText().trim(); String sid = jtfip11.getText().trim(); //String code = jtfport11.getText().trim(); driver = "oracle.jdbc.driver.OracleDriver"; url = "jdbc:oracle:thin:@" + ip + ":" + port + ":" + sid; //javax.swing.JOptionPane.showMessageDialog(null,username+" "+password+" "+url); // RegisterUtil.putStringSystemRoot("oracle.driver", // driver); // RegisterUtil.putStringSystemRoot("oracle.url", url); // RegisterUtil.putStringSystemRoot("oracle.username", // username); // RegisterUtil.putStringSystemRoot("oracle.password", // password); System.out.println(RegisterUtil .getStringFromSystemRoot("oracle.driver")); System.out.println(driver); System.out.println(url); System.out.println(username); System.out.println(password); logger.info(driver); try { conn = DriverManager.getConnection(url, username, password); if (conn != null) { System.out.println(conn); conn.setAutoCommit(getAutoCommit()); connHolder.set(conn); linkBtn.setText("u521Du59CBu5316u6210u529FuFF01u8BF7u5173u95EDu7A97u4F53!"); //RegisterUtil.putIntSystemRoot("isInit", 0); } } catch (Exception e2) { logger.error(e2.getMessage()); } finally{ if(conn!=null){ try { conn.close(); } catch (SQLException e1) { logger.error(e1.getMessage()); } } } } }; linkBtn.addMouseListener(linkServerListener); } }; t_oracle.start(); } } private void initJFrame_mysql(final String jfTitle, String databasetype) { if(databasetype.equals("mysql")){ Thread t_mysql = new Thread() { public void run() { String title; Font fontGlobal = new Font("u6977u4F53", 11, 10); if (jfTitle != null && !"".equals(jfTitle) && !"null".equals(jfTitle)) { title = "mysqlu6570u636Eu5E93u521Du59CBu5316:" + jfTitle; } else { title = "mysqlu6570u636Eu5E93u521Du59CBu5316"; } JFrame jf = new JFrame(title); jf.setVisible(true); jf.setBounds(600, 260, 266, 166); // jf.setBounds(600, 260, 266, 366); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.HIDE_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 jls2 = new JLabel("u4E3Bu673Au540D/ip:"); jls2.setBounds(0, 5, 50, 45); jpanel.add(jls2); jls2.setFont(fontGlobal); 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("u7AEFu53E3:"); 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("u7528u6237u540D:"); 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("u5BC6u7801:"); 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("u6570u636Eu5E93u540D:"); jls6.setBounds(6, 65, 50, 45); jpanel.add(jls6); jls6.setFont(fontGlobal); final JTextField jtfip11 = new JTextField(18); jtfip11.setBounds(50, 77, 58, 20); jpanel.add(jtfip11); jtfip11.setText("test"); JLabel jls51 = new JLabel("u7F16u7801:"); jls51.setBounds(123, 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("u521Du59CBu5316DButilsu5DE5u5177u7C7B"); linkBtn.setBounds(56, 111, 150, 20); jpanel.add(linkBtn); linkBtn.setMargin(new Insets(0, 0, 0, 0));// u8FD9u6837u8BBEu7F6Ebuttonu4E2Du7684u5B57u4F53u4E0Ebuttonu65E0u4E0Au4E0Bu8FB9u8DDD linkBtn.setFont(fontGlobal); MouseAdapter linkServerListener = new MouseAdapter() { public void mouseClicked(MouseEvent e) { String ip = jtfip.getText().trim(); int port = Integer.parseInt(jtfport.getText() .trim()); username = jtfip1.getText().trim(); password = jtfport1.getText().trim(); String databaseName = jtfip11.getText().trim(); String code = jtfport11.getText().trim(); driver = "com.mysql.jdbc.Driver"; url = "jdbc:mysql://" + ip + ":" + port + "/" + databaseName + "?unicode\=true&characterEncoding\=" + code; RegisterUtil.putStringSystemRoot("mysql.driver", driver); RegisterUtil.putStringSystemRoot("mysql.url", url); RegisterUtil.putStringSystemRoot("mysql.username", username); RegisterUtil.putStringSystemRoot("mysql.password", password); System.out.println(RegisterUtil .getStringFromSystemRoot("mysql.driver")); System.out.println(driver); System.out.println(url); System.out.println(username); System.out.println(password); try { conn = DriverManager.getConnection(url, username, password); if (conn != null) { conn.setAutoCommit(getAutoCommit()); connHolder.set(conn); linkBtn.setText("u521Du59CBu5316u6210u529FuFF01u8BF7u5173u95EDu7A97u4F53"); RegisterUtil.putIntSystemRoot("isInit", 0); } } catch (Exception e2) { e2.printStackTrace(); } } }; linkBtn.addMouseListener(linkServerListener); } }; t_mysql.start(); } } } /** * @category u83B7u53D6u6240u6709u7684u6570u636Eu5E93u540D * @return List<String> */ public static List<String> getAllDatabaseNames() { List<String> list = new ArrayList<String>(); try { ResultSet rs = DButils.getConnection().prepareStatement( "show databases").executeQuery(); while (rs.next()) { list.add(rs.getString(1)); } rs.close(); } catch (SQLException e) { init(); log.WriteLine("DButils.getAllDatabaseNames()", "getAllDatabaseNames error"); exceptionPrint(e); } return list; } /** * @category u7ED9u8DDDsqlu8BEDu53E5u8FD4u56DEResultSetu96C6u5408 * @param sqlu8BEDu53E5 * sql * @return u67E5u8BE2u8FD4u56DEu7684u96C6u5408 */ public static ResultSet getResultSet(String sql) { ResultSet rs = null; try { rs = getConnection().createStatement().executeQuery(sql); } catch (SQLException e) { log.WriteLine("DButils.getResultSet()", "getResultSet error"); exceptionPrint(e); } return rs; } /** * @category u6279u5904u7406sqklu8BEDu53E5 * @param sqls * u8981u6267u884Cu7684sqlu8BEDu53E5 * @return int[] u6267u884CBatchu540Eu7684u6570u7EC4 */ public static int[] updateStatement(String[] sqls) { Statement st = null; int result[] = null; try { st = getConnection().createStatement(); for (int i = 0; i < sqls.length; i++) { st.addBatch(sqls[i]); } result = st.executeBatch(); st.close(); st = null; } catch (SQLException e) { st = null; log.WriteLine("DButils.update()", "update error"); exceptionPrint(e); } return result; } /** * * @param c * Person class * @param fromNumber * litmi from * @param number * to * @param columnName * u8868u4E2Du7684u5217u540D * @param orderby * u6309u4EC0u4E48u6392u5E8F * @return */ public static List getEntitysLimitOderBy(Class c, int fromNumber, int number, String columnName, String orderby) { String tableName = c.getSimpleName().toLowerCase();// person u8868u7684u540Du5B57 if (!isTableExist(tableName)) { System.err.println("u8868'" + tableName + "'u4E0Du5B58u5728"); return null; } List<String> columnList = getColumns(c); if (!columnList.contains(columnName)) { System.err.println("u5217u540D'" + columnName + "'u4E0Du5B58u5728"); log.WriteLine("DButils.getEntitysLimitOderBy()", columnName + " is not isExist! u9000u51FA"); return null; } if (orderby == null || (!orderby.equalsIgnoreCase("asc") && !orderby .equalsIgnoreCase("desc"))) { log.WriteLine("DButils.getEntitysLimitOderBy()", "u6392u5E8Fu5173u952Eu5B57u9519u8BEF"); return null; } List list = new ArrayList(); PreparedStatement ps = null; ResultSet rs = null; Field[] fields = c.getFields();// u83B7u53D6u6240u6709u7684publicu5C5Eu6027 if (fields.length == 0) { // fields=c.getDeclaredFields();//u83B7u53D6u6240u6709u7684privateu5C5Eu6027 fields = c.getDeclaredFields();// u83B7u53D6get set u65B9u6CD5 } StringBuilder sql = new StringBuilder("select * from ").append( tableName).append(" order by ").append(columnName + " ") .append(orderby).append(" limit ?,?"); log.WriteLine("DButils.getEntitysLimitOderBy()", "sql:" + sql.toString()); try { if (!isTableExist(tableName)) { System.err.println("u8868u4E0Du5B58u5728"); return list; } ps = (PreparedStatement) getConnection().prepareStatement( sql.toString()); ps.setInt(1, fromNumber); ps.setInt(2, number); rs = ps.executeQuery(); System.out.println(" " + ps.toString().split(":")[1]); log.WriteLine("DButils.getEntitysLimitOderBy()", 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) { log.WriteLine("DButils.getEntitysLimitOderBy()", "getEntitysLimitOderBy error"); exceptionPrint(e); } finally { rs = null; ps = null; } return list; } public static void main(String[] args) { getAllDatabaseNames(); String[] sqls = new String[] { "update person set name='u6211' , address='fq' where id=1", "update person set name='u4F60', tel='13781910922' where id=2" }; System.out.println(getEntitysLimitOderBy(com.ctl.bean.Person.class, 1, 2, "id", "asc")); // isExecuteInit(true); // System.out.println(Arrays.toString(updateStatement(sql))); } }

    #database=mysql
    #u6570u636Eu5E93u7684u7C7Bu578Bu5FC5u9700u914Du7F6Eu6B63u786E
    databasetype=oracle
    #mysql config
    mysql.driver=com.mysql.jdbc.Driver
    mysql.url=jdbc:mysql://localhost:3306/test?unicode=true&characterEncoding=utf8
    mysql.username=root
    mysql.password=root
    
    #oracle config
    oracle.driver=oracle.jdbc.driver.OracleDriver
    oracle.url=jdbc:oracle:thin:@localhost:1521:orcl
    oracle.username=test
    oracle.password=test
    
    #ftp client config
    ftp.host=127.0.0.1
    ftp.port=21
    ftp.username=grg
    ftp.password=grg
    ftp.binaryTransfer= true
    ftp.passiveMode=true
    ftp.encoding=gbk
    ftp.clientTimeout=30000
    


  • 相关阅读:
    Thinkphp随堂笔记【模型初步上】
    Thinkphp随堂笔记【MVC模式和URl访问的四种方式】
    C# set get 个人学习笔记
    关于文件的操作r、r+、w、w+
    HTTPS的通信步骤02
    HTTPS的通信步骤01
    python六剑客之reduce()函数
    python六剑客之filter()函数
    python六剑客之map()函数
    TCP/IP四层模型
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5184904.html
Copyright © 2011-2022 走看看