码迷,mamicode.com
首页 > 数据库 > 详细

JAVA操作mysql(如何更加面向对象的操作数据库)

时间:2014-12-05 12:29:06      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   java   

既然谈到面向对象,所以,先把连接信息给搞个对象出来:

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(如何更加面向对象的操作数据库)

标签:style   blog   io   ar   color   os   sp   for   java   

原文地址:http://www.cnblogs.com/zhangfei/p/4146272.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!