JAVA操作mysql(如何更加面向对象的操作数据库)
既然谈到面向对象,所以,先把连接信息给搞个对象出来:
public class DBInfo { private String driver; private String host; private String port; private String user; private String pwd; private String dataBase; public DBInfo(){ this.driver = "com.mysql.jdbc.Driver"; this.host = ""; this.port = ""; this.user = ""; this.pwd = ""; this.dataBase = ""; } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public String getHost() { return host; } public void setHost(String host) { this.host = host; } public String getDataBase() { return dataBase; } public void setDataBase(String dataBase) { this.dataBase = dataBase; } public String getPort() { return port; } public void setPort(String port) { this.port = port; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }
既然是操作数据库,我们就把数据库的字段给对象化一下,也就是持久化:在定义变量时,我们搞个约定,比如,数据库字段名为:test_login_name,则定义变量时为:testLoginName.
public class UserInfo { private int id; private String testName; private String testAge; private String testHeight; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTestName() { return testName; } public void setTestName(String testName) { this.testName = testName; } public String getTestAge() { return testAge; } public void setTestAge(String testAge) { this.testAge = testAge; } public String getTestHeight() { return testHeight; } public void setTestHeight(String testHeight) { this.testHeight = testHeight; } }
好,现在有了javabean,有了数据库连接的对象了,再加一个枚举来保存数据库与bean之间的映射关系:
public enum TableBean { USER_INFO("com.test.bean.UserInfo"); private String value; private TableBean(String value){ this.value = value; } public String getValue(){ return value; } @Override public String toString() { return value; } public static void main(String[] args){ System.out.println(TableBean.USER_INFO); } }
再加一个保存ResultSetMetaData信息的类:
public class MetaData { public static Map<String, ResultSetMetaData> metaData = new HashMap<String, ResultSetMetaData>(); }
余下就是操作数据库了:
public class ConnectToMySQL { private DBInfo dbInfo; private Connection conn = null; private Statement stmt = null; public ConnectToMySQL(){ dbInfo = new DBInfo(); } public DBInfo getDbInfo() { return dbInfo; } public void setDbInfo(DBInfo dbInfo) { this.dbInfo = dbInfo; } public void connect() { this.close(); this.connectMySQL(); } public synchronized void close() { try { if (stmt != null) { stmt.close(); stmt = null; } if (conn != null) { conn.close(); conn = null; } } catch (SQLException e) { e.printStackTrace(); } } private synchronized void connectMySQL() { try { Class.forName(dbInfo.getDriver()).newInstance(); conn = (Connection) DriverManager.getConnection("jdbc:mysql://" + dbInfo.getHost() + "/" + dbInfo.getDataBase() +"?useUnicode=true&characterEncoding=utf-8", dbInfo.getUser(),dbInfo.getPwd()); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } private void statement() { if (conn == null) { this.connectMySQL(); } try { stmt = (Statement) conn.createStatement(); } catch (SQLException e) { e.printStackTrace(); } } private ResultSet resultSet(String sql) { ResultSet rs = null; if (stmt == null) { this.statement(); } try { rs = stmt.executeQuery(sql); } catch (SQLException e) { e.printStackTrace(); } return rs; } private void executeUpdate(String sql){ if (stmt == null) { this.statement(); } try { stmt.executeUpdate(sql); } catch (SQLException e) { System.out.println(sql); e.printStackTrace(); } } public List<Object> query(String tableInfo, String sql) { List<Object> list = new ArrayList<Object>(); ResultSet rs = this.resultSet(sql); try { ResultSetMetaData md = rs.getMetaData(); int cc = md.getColumnCount(); while (rs.next()) { Object object = this.getBeanInfo(tableInfo); for (int i = 1; i <= cc; i++) { String cn = md.getColumnName(i); this.reflectSetInfo(object, this.changeColumnToBean(cn,"set"), rs.getObject(cn)); } list.add(object); } } catch (SQLException e) { e.printStackTrace(); } return list; } public void insert(String table, Object object){ String sql = ""; try { this.getMetaData(table); ResultSetMetaData md = MetaData.metaData.get(table); int cc = md.getColumnCount(); String insertColumn = ""; String insertValue = ""; for (int i = 2; i <= cc; i++) { String cn = md.getColumnName(i); Object gValue = this.reflectGetInfo(object, this.changeColumnToBean(cn,"get")); if(gValue.getClass().getSimpleName().equals("String")){ gValue = "\""+gValue+"\""; } if("".equals(insertColumn)){ insertColumn += cn; insertValue += gValue; }else{ insertColumn += ","+cn; insertValue += ","+gValue; } } sql = "insert into "+table+" ("+insertColumn+") values ("+insertValue+")"; this.executeUpdate(sql); } catch (SQLException e) { e.printStackTrace(); } } private void getMetaData(String table){ if(!MetaData.metaData.containsKey(table)){ ResultSet rs = this.resultSet("select * from "+table+" limit 0,1"); try { MetaData.metaData.put(table, rs.getMetaData()); } catch (SQLException e) { e.printStackTrace(); } } } private Object getBeanInfo(String tableInfo){ Object object = null; try { object = Class.forName(tableInfo).newInstance(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } return object; } private void reflectSetInfo(Object object, String methodName, Object parameter){ try { Class<? extends Object> ptype = parameter.getClass(); if(parameter.getClass().getSimpleName().equals("Integer")){ ptype = int.class; } Method method = object.getClass().getMethod(methodName, ptype); method.invoke(object, parameter); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } private Object reflectGetInfo(Object object, String methodName){ Object value = null; try { Method method = object.getClass().getMethod(methodName); Object returnValue = method.invoke(object); if(returnValue!=null){ value = returnValue.toString(); }else{ value = ""; } } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return value; } private String columnToBean(String column){ if(column.contains("_")){ int index = column.indexOf("_"); String beanName = column.substring(0, index) +column.substring(index+1, index+2).toUpperCase() +column.substring(index+2, column.length()); return beanName; } return column; } private String changeColumnToBean(String column, String ext){ String[] col = column.split("_"); for (int i = 0; i < col.length; i++) { column = this.columnToBean(column); } column =column.replaceFirst(column.substring(0, 1), column.substring(0, 1).toUpperCase()); column = ext+column; return column; } public static void main(String[] args) throws SQLException { ConnectToMySQL c = new ConnectToMySQL(); c.connect(); List<Object> list = c.query(TableBean.APK_INFO.toString(), "select * from user_info"); c.insert("user_info", (UserInfo)list.get(0)); c.close(); } }
仔细看看吧,query出来就是对象的集合,insert时,就是表名与对象就行了,至于update与delete,大家自已扩展吧!
如果把这个摸清楚,spring操作mysql数据库的原理,你也就差不多了!
点亮测试人生!QQ:408129370
百度阅读电子书地址:http://yuedu.baidu.com/ebook/f6dbb2a2f01dc281e53af0f3
讨论QQ群:536192476
个人公众号:
百度阅读电子书地址:http://yuedu.baidu.com/ebook/f6dbb2a2f01dc281e53af0f3
讨论QQ群:536192476
个人公众号: