1. 程式人生 > >Java與MySQL連線的工具類JDBCUTils

Java與MySQL連線的工具類JDBCUTils

幾種JDBCUtils

第一種

public class JDBCUtils {
    public static  String driver;
    public static String url;
    public static String user;
    public static String password;
    static{
        try {
            Properties pro=new Properties();
            //jdbc.properties一般是放在src目錄下的配置檔案具體內容下面給出
            pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties"));
            driver = pro.getProperty("driver");
            url = pro.getProperty("url");
            user = pro.getProperty("user");
            password = pro.getProperty("password");
            Class.forName(driver);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
	//獲取Connection物件
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url,user,password);
    }
	//關閉資源
    public static void close(PreparedStatement pstat,Connection conn){
        if(pstat!=null){
            try {
                pstat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(ResultSet rs,PreparedStatement pstat, Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        close(pstat,conn);
    }

}
jdbc.properties攥寫方法:
在src目錄下建立jdbc.properties文件裡面內容如下:
url=jdbc:mysql:///db3
user=root
password=root
driver=com.mysql.jdbc.Driver
注意:不能有多餘空格;db3為資料庫名;兩個root分別是MySQL安裝時的使用者名稱和密碼

這種使用的時候直接JDBCUtils.getConnection()獲取連線物件,然後根據連線物件獲取執行物件執行你寫的SQL語句;但這個使用的少 ,一般連線池用的多,例如C3P0連線池或者阿里的Druid連線池,我用阿里的這個多一點。druid具體用法如下 :
需要導的jar包如下:
jar包
裡面有些不需要的 例如c3p0那個:
DruidJDBCUtils工具類程式碼:

public class DruidJDBCUtils {
   /* 1. 步驟:
        1. 匯入jar包 druid-1.0.9.jar
		2. 定義配置檔案:
            * 是properties形式的
			* 可以叫任意名稱,可以放在任意目錄下
		3. 載入配置檔案。Properties
		4. 獲取資料庫連線池物件:通過工廠來來獲取  DruidDataSourceFactory
		5. 獲取連線:getConnection
		*/
    private static DataSource ds;
    static {

        try {
            //載入配置檔案JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")

            Properties pro=new Properties();
            pro.load(DruidJDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  獲取連線物件 Connection conn
     * @return conn
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /**
     * 回收資源(兩個引數)
     * @param pstat
     * @param conn
     */
    public static void close(PreparedStatement pstat, Connection conn){
        close(null,pstat,conn);
    }

    /**
     * 回收資源(三個引數)
     * @param rs
     * @param pstat
     * @param conn
     */
    public static void close(ResultSet rs, PreparedStatement pstat, Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(pstat!=null){
            try {
                pstat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 返回DataSource 物件 ds
     * @return DataSource
     */
    public static DataSource getDataSource(){
        return ds;
    }

}

這段程式碼是需要配置檔案的:首先在src目錄下建立druid.properties檔案
內容如下:
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db3
username=root
password=root
initialSize=5
maxActive=10
maxWait=3000

這樣,工具類就建好了,下面我們來使用吧.

一般結合Template來使用,有很多很好用的方法很方便:
注意:這裡用的測試類來簡單使用的,具體使用有略微不同,視具體情況而定。

public class JDBCTemplateDemo01 {
    DataSource ds= DruidJDBCUtils.getDataSource();
    JdbcTemplate template=new JdbcTemplate(ds);

    /**
     * 使用template進行插入操作
     **/
    @Test
    public void test01(){
        String sql="insert into user values (null,?,?)";
        template.update(sql,"Jeson","123");
    }

    /**
     * update
     */
    @Test
    public void test02(){
        String sql="update user set username=? where id=4";
        template.update(sql,"Jim");
    }

    /**
     * delete
     */
    @Test
    public void test03(){
        String sql="delete from user where id=5";
        template.update(sql);
    }
    /**
     * 測試用 queryForMap()
     */
    @Test
    public void test04(){
        String sql="select * from user where id=?";
        Map<String, Object> stringObjectMap = template.queryForMap(sql, 3);
        System.out.println(stringObjectMap);

    }
    /**
     * 測試queryForList()
     */
    @Test
    public void test05(){
        String sql="SELECT * FROM user";
        List<Map<String, Object>> maps = template.queryForList(sql);
        for (Map<String, Object> map : maps) {
            System.out.println(map);
        }
    }
    /**
     * 6.1 查詢所有記錄,將其封裝為Emp物件的List集合,自己實現mapRow
     */
    @Test
    public void test06_1(){
        String sql="select * from user";
        List<User> list = template.query(sql, new RowMapper<User>() {
            @Override
            public User mapRow(ResultSet rs, int i) throws SQLException {
                return new User(rs.getInt("id"),rs.getString("username"),rs.getString("password"));
            }
        });
        for (User user : list) {
            System.out.println(user);
        }
    }
    /**
     * 6.2 查詢所有記錄,將其封裝為Emp物件的List集合使用new BeanPropertyRowMapper<型別>(型別.class)
     */
    @Test
    public void test06_2(){
        String sql="select * from user";
        List<User> query = template.query(sql, new BeanPropertyRowMapper<User>(User.class));
        
        for (User user : query) {
            System.out.println(user);
        }
    }
    /**
     * 7. 查詢總記錄數
     */
    @Test
    public void test07(){
        String sql="select count(id) from user";
        Long aLong = template.queryForObject(sql, Long.class);
        System.out.println(aLong);
    }
}