JAVA JBDC+開源工具連接MySql數據庫示例心得二

使用數據庫連接池連接數據庫,還使用了一些開源工具簡化上一次的JDBC開發,下面是代碼示例:
這裏寫圖片描述
先看DBCH數據庫連接池的配置文件的內容:

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/userdb?useUnicode=true&characterEncoding=utf-8&useSSL=false
username=root
password=123456

dataSource.initialSize=20  

dataSource.maxIdle=20  

dataSource.minIdle=5  

dataSource.maxActive=100  

dataSource.logAbandoned=true  

dataSource.removeAbandoned=true

dataSource.removeAbandonedTimeout=180

dataSource.maxWait=1000

A.java的代碼片,裏面的屬性與數據庫的字段名一樣,是數據庫的映射對象類

package JDBCDAO;

public class A {

    private int id;
    private String name;
    private String password;
    private String email;

    public A() {

    }

    public A(int id, String name, String password, String email) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.email = email;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String toString() {
        return "A [id=" + id + ", name=" + name + ", password=" + password + ", email=" + email + "]";
    }

}

然後先看JDBCTools.java數據庫連接的代碼操作:

package JDBCDAO;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;

public class JDBCTools {
    /**
     * 使用DBCP連接池連接數據庫 
     * @return Connection
     */
    public static Connection GetdbcpConnection(){
        Connection connection = null;
        try {
            Properties properties = new Properties();
            //獲取配置文件流
            InputStream in = JDBCTools.class.getClassLoader().getResourceAsStream("dbcp.properties");
            properties.load(in);
            BasicDataSource basicDataSource = BasicDataSourceFactory.createDataSource(properties);// 得到一個連接池對象
            connection = basicDataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
    /**
     * 關閉connection連接,statement連接,resultSet連接 
     */
    public static void CloseCSR(Connection connection,Statement statement,ResultSet resultSet){
        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 開始事務
     */
    public static void setAutoCommit(Connection connection){
        try {
            connection.setAutoCommit(false);
            System.out.println("開始事務");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * 提交事務
     */
    public static void commit(Connection connection){
        try {
            connection.commit();
            System.out.println("提交事務");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * 回滾事務
     */
    public static void rollback(Connection connection){
        try {
            connection.rollback();
            System.out.println("回滾事務");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

在看DAO.java,最後寫了幾個查詢數據的方式,還望提高哈。。。。。

package JDBCDAO;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

/**
 * 訪問數據的DAO 定義好訪問數據表的各種方法
 * 
 * @param T:DAO處理實體類的類型
 */
public class DAO {
    private QueryRunner queryRunner = null;

    public DAO() {
        queryRunner = new QueryRunner();
    }
    /**
     * 返回一個List<A>的列表裏面存儲了與數據庫映射的數據 
     * 就是將數據庫所有結果集與A類映射,List裝下所有A對象,一個A類對應一條字段
     */
    @SuppressWarnings("unchecked")
    public List get(Class clazz, Connection connection, String sql, Object... objects)
            throws SQLException, InstantiationException, IllegalAccessException {
        List<A> as = null;
        if (objects == null){
            as = (List<A>) queryRunner.query(connection, sql, new MyResultsethandler(clazz));
        } else {
            as = (List<A>) queryRunner.query(connection, sql, new MyResultsethandler(clazz), objects);
        }
        return as;

    }

    /**
     * 返回查詢到的所有數據Map集合的結果集 返回所有查詢到的列
     * 
     */
    public List getListMapValues(Connection connection, String sql, Object... objects) throws SQLException {
        List<Map<String, Object>> values = null;
        if (objects == null) {
            values = queryRunner.query(connection, sql, new MapListHandler());
        } else {
            values = queryRunner.query(connection, sql, new MapListHandler(), objects);
        }
        return values;
    }

    /**
     * 返回查詢到的一條數據或第一條數據的Map集合的結果集; 只返回一條數據
     *
     */
    public Map<String, Object> getMapValue(Connection connection, String sql, Object... objects)
            throws SQLException, IllegalAccessException, InvocationTargetException, InstantiationException,
            NoSuchMethodException, SecurityException {
        Map<String, Object> values = null;
        if (objects == null) {
            values = queryRunner.query(connection, sql, new MapHandler());
        } else {
            values = queryRunner.query(connection, sql, new MapHandler(), objects);
        }
        return values;
    }

    /**
     * 更新數據操作 INSERT,UPDATE,DELETE
     */
    public void Update(Connection connection, String sql, Object... objects) throws SQLException {
        if (objects == null) {// 不帶佔位符的SQL語句
            queryRunner.update(connection, sql);
        } else {// 帶佔位符的SQL語句
            queryRunner.update(connection, sql, objects);
        }

    }
}
/**
 * 實現ResultSetHandler接口,返回List數據給上面用
 * 數據庫映射對象
 */
class MyResultsethandler implements ResultSetHandler {
    Class clazz = null;

    public MyResultsethandler(Class clazz) throws InstantiationException, IllegalAccessException {
        this.clazz = clazz;
    }

    @Override
    public Object handle(ResultSet rs) throws SQLException {
        List<Object> liClazz = new ArrayList();//List存儲對象
        Map<String, Object> map = null;//存儲一條字段
        Object object = null;//用於反射實例化
        List<Map<String, Object>> listMap = new ArrayList();//將所有Map集合存於List裏面
        ResultSetMetaData data = rs.getMetaData();
        while (rs.next()) {
            map = new HashMap<String, Object>();
            for (int i = 0; i < data.getColumnCount(); i++) {
                String columnLabel = data.getColumnLabel(i + 1);// 得到列名
                Object columnValue = rs.getObject(i + 1);// 得到值
                map.put(columnLabel, columnValue);
            }
            listMap.add(map);
        }
        if (listMap.size() > 0) {
            for (int i = 0; i < listMap.size(); i++) {
                try {
                    object = clazz.newInstance();
                    for (Map.Entry<String, Object> entry : listMap.get(i).entrySet()) {
                        String fieldName = entry.getKey();
                        Object value = entry.getValue();
                        BeanUtils.setProperty(object, fieldName, value);
                    }
                    liClazz.add(object);
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }

            }

        }
        return liClazz;
    }
}

JDBC的學習到這裏就結束了,接下來學習Hibernate等框架的使用。。。。

發佈了64 篇原創文章 · 獲贊 42 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章