常用公共類代碼一之數據庫的連接 – JAVA編程語言程序開發技術文章

在項目中,我們經常會寫到一些公共的代碼,來讓開發人員調用,減少代碼重復,下面,我就將一些常用到的公共類貼出來和大傢分享!!
一、數據庫的連接,常用的方式有直接將那些要連接的參數放到java類中、將連接參數放到Properties文件中或者放到XML文件中,下面一一為大傢描述
1、直接連接:
[java]
<span style="font-size:18px;">        普通的配置方式 
    public static Connection getConnection(){ 
        Connection conn=null; 
        try { 
            Class.forName("com.mysql.jdbc.Driver"); 
            String url="jdbc:mysql://127.0.0.1:3306/xinyuandb"; 
            String username="root"; 
            String password="123456"; 
            conn=DriverManager.getConnection(url, username, password); 
        } catch (ClassNotFoundException e) { 
            e.printStackTrace(); 
        } catch (SQLException e) { 
            e.printStackTrace(); 
        } 
        return conn; 
    }</span>  www.aiwalls.com

2、通過Properties文件創建連接,好處,很靈活,不用在代碼裡面進行更改
  創建jdbc.properties文件
  driver=com.mysql.jdbc.Driver
  url=jdbc\:mysql\://127.0.0.1\:3306/xinyuandb
  username=root
  password=123456
[java]
<span style="font-size:18px;">        從properties文件中讀取 
    public static Connection getConnection(){ 
        Connection conn=null; 
        Properties p=new Properties(); 
        try { 
            //從當前線程加載 
            p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties")); 
            Class.forName(p.getProperty("driver")); 
            conn=DriverManager.getConnection(p.getProperty("url"), p.getProperty("username"), p.getProperty("password")); 
        } catch (IOException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } catch (ClassNotFoundException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } catch (SQLException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        } 
        return conn; 
    } 
 
<span style="color:#FF0000;">3、通過XML文件讀取</span> 
  創建jdbc.xml文件 
<?xml version="1.0" encoding="UTF-8"?> 
<config> 
    <jdbc-config> 
      <driver>com.mysql.jdbc.Driver</driver> 
      <url>jdbc:mysql://127.0.0.1:3306/xinyuandb</url> 
      <username>root</username> 
      <password>123456</password> 
    </jdbc-config> 
</config> 
創建javaBean類 
package com.common.db; 
 
public class JdbcBean { 
    private String driver; 
    private String url; 
    private String username; 
    private String password; 
    public String getDriver() { 
        return driver; 
    } 
    public void setDriver(String driver) { 
        this.driver = driver; 
    } 
    public String getUrl() { 
        return url; 
    } 
    public void setUrl(String url) { 
        this.url = url; 
    } 
    public String getUsername() { 
        return username; 
    } 
    public void setUsername(String username) { 
        this.username = username; 
    } 
    public String getPassword() { 
        return password; 
    } 
    public void setPassword(String password) { 
        this.password = password; 
    } 

 
創建XML解析類 
</span><pre name="code" class="java"><span style="font-size:18px;">package com.common.db; 
 
import org.dom4j.Document; 
import org.dom4j.DocumentException; 
import org.dom4j.Element; 
import org.dom4j.io.SAXReader; 
 
public class XmlConfigReader { 
    private static XmlConfigReader instance; 
    private JdbcBean bean=null; 
    //調用構造函數進行XML文件解析 
    private XmlConfigReader(){ 
        SAXReader reader=new SAXReader(); 
        try { 
            Document doc=reader.read(Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.xml")); 
            Element root=doc.getRootElement(); 
            Element first=root.element("jdbc-config"); 
            String driver=first.element("driver").getText(); 
            String url=first.element("url").getText(); 
            String username=first.element("username").getText(); 
            String password=first.element("password").getText(); 
            bean=new JdbcBean(); 
            bean.setDriver(driver); 
            bean.setUrl(url); 
            bean.setUsername(username); 
            bean.setPassword(password); 
        } catch (DocumentException e) { 
            e.printStackTrace(); 
        } 
    } 
     
    public synchronized static XmlConfigReader getInstance(){ 
        if(instance==null){ 
            instance=new XmlConfigReader(); 
        } 
        return instance; 
    } 
     
    public JdbcBean getJdbeanBean(){ 
        return bean; 
    } 
 

</span> 

// 從XML文件中讀取配置取得同一Connection
//    static Connection conn=null;
//    static{
//        JdbcBean jdbc=XmlConfigReader.getInstance().getJdbeanBean();
//        try {
//            Class.forName(jdbc.getDriver());
//            conn=DriverManager.getConnection(jdbc.getUrl(), jdbc.getUsername(),jdbc.getPassword());
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
//    }

    //從XML文件中讀取配置
    public static Connection getConnection(){
        Connection conn=null;
        JdbcBean jdbc=XmlConfigReader.getInstance().getJdbeanBean();
        try {
            Class.forName(jdbc.getDriver());
            conn=DriverManager.getConnection(jdbc.getUrl(), jdbc.getUsername(),jdbc.getPassword());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
有時候我們想取得Connection的單實例,又不會影響到其安全性,我們可以通過線程ThreadLocal來對Connection進行管理:
[java]
<span style="font-size:18px;">package com.common.db; 
 
import java.sql.Connection; 
 
/**
 * 線程管理
 * @author Administrator
 *
 */ 
public class ConnectionManager { 
    //使用線程變量對Connection進行管理 
    private static ThreadLocal<Connection> local=new ThreadLocal<Connection>(); 
     
    public static Connection getConnection(){ 
        Connection conn=local.get(); 
        if(conn==null){ 
            conn=DbUtil.getConnection(); 
            local.set(conn); 
        } 
        return conn; 
    } 
    public static void main(String[] args) { 
        Connection conn1=ConnectionManager.getConnection(); 
        Connection conn2=ConnectionManager.getConnection(); 
        Connection conn3=DbUtil.getConnection(); 
        Connection conn4=DbUtil.getConnection(); 
        System.out.println(conn1==conn2);//true 
        System.out.println(conn3==conn4);//false 
    } 

</span> 

這樣,數據庫操作的公共類基本上實現瞭,大傢在項目中就可以進行調用瞭,當然,還有一些基本的流的關閉和事物的處理,代碼如下:
[java] 
<span style="font-size:18px;">       public static void close(Connection conn) { 
        if (conn != null) { 
            try { 
                conn.close(); 
            } catch (SQLException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 
     
    public static void close(Statement pstmt) { 
        if (pstmt != null) { 
            try { 
                pstmt.close(); 
            } catch (SQLException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 
     
    public static void close(ResultSet rs ) { 
        if (rs != null) { 
            try { 
                rs.close(); 
            } catch (SQLException e) { 
                e.printStackTrace(); 
            } 
        } 
    } 
     
    public static void beginTransaction(Connection conn) { 
        try { 
            if (conn != null) { 
                if (conn.getAutoCommit()) { 
                    conn.setAutoCommit(false); //手動提交 
                } 
            } 
        }catch(SQLException e) {} 
    } 
                 
    public static void commitTransaction(Connection conn) { 
        try { 
            if (conn != null) { 
                if (!conn.getAutoCommit()) { 
                    conn.commit(); 
                } 
            } 
        }catch(SQLException e) {} 
    } 
     
    public static void rollbackTransaction(Connection conn) { 
        try { 
            if (conn != null) { 
                if (!conn.getAutoCommit()) { 
                    conn.rollback(); 
                } 
            } 
        }catch(SQLException e) {} 
    } 
     
    public static void resetConnection(Connection conn) { 
        try { 
            if (conn != null) { 
                if (conn.getAutoCommit()) { 
                    conn.setAutoCommit(false); 
                }else { 
                    conn.setAutoCommit(true); 
                } 
            } 
        }catch(SQLException e) {} 
    }</span> 

 作者:HarderXin

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。