首页 > 代码库 > JAVA操作mysql(如何更加面向对象的操作数据库)
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,有了数据库连接的对象了,余下就是操作数据库了:
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<UserInfo> query(String sql) { List<UserInfo> list = new ArrayList<UserInfo>(); ResultSet rs = this.resultSet(sql); try { ResultSetMetaData md = rs.getMetaData(); int cc = md.getColumnCount(); while (rs.next()) { UserInfo userInfo = new UserInfo(); for (int i = 1; i <= cc; i++) { String cn = md.getColumnName(i); if(cn.equals("id")){ userInfo.setId(rs.getInt("id")); }else{ this.reflectSetInfo(userInfo, this.changeColumnToBean(cn,"set"), rs.getString(cn)); } } list.add(userInfo); } } catch (SQLException e) { e.printStackTrace(); } return list; } public void insert(String table, UserInfo userInfo){ ResultSet rs = this.resultSet("select * from "+table+" limit 0,1"); ResultSetMetaData md; String sql = ""; try { md = rs.getMetaData(); int cc = md.getColumnCount(); String insertColumn = ""; String insertValue = ""; for (int i = 1; i <= cc; i++) { String cn = md.getColumnName(i); if(!cn.equals("id")){ String gValue = this.reflectGetInfo(userInfo, this.changeColumnToBean(cn,"get")); 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 reflectSetInfo(UserInfo userInfo, String methodName, String parameter){ try { Method method = userInfo.getClass().getMethod(methodName, String.class); method.invoke(userInfo, 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 String reflectGetInfo(UserInfo userInfo, String methodName){ String value = null; try { Method method = userInfo.getClass().getMethod(methodName); Object returnValue = method.invoke(userInfo); 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<UserInfo> list = c.query("select * from user_info"); c.insert("user_info", list.get(0)); c.close(); }}
仔细看看吧,query出来就是对象的集合,insert时,就是表名与对象就行了,至于update与delete,大家自已扩展吧!
如果把这个摸清楚,spring操作mysql数据库的原理,你也就差不多了!
JAVA操作mysql(如何更加面向对象的操作数据库)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。