首页 > 代码库 > java中简单的db封装

java中简单的db封装

package com.melin.bbs; 
 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 


public class DB {

//建立连接

    public static Connection getConn(){ 
        Connection conn=null; 
        try { 
            Class.forName("com.mysql.jdbc.Driver"); 
        } catch (ClassNotFoundException e) { 
           e.printStackTrace(); 

        } 
        try { 
       conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/bbs","root","root"); 
        } catch (SQLException e) { 
            e.printStackTrace(); 
        } 
        return conn; 
    } 
    

//SQL语句发送到数据库

     public static Statement getStmt(Connection conn){ 
        Statement stmt=null; 
        try { 
            stmt=conn.createStatement(); 
        } catch (SQLException e) { 
           e.printStackTrace(); 
        } 
        return stmt; 
    }


//返回结果集
    public static ResultSet getRs(Statement stmt,String sql){ 
        ResultSet rs=null; 
        try { 
            rs=stmt.executeQuery(sql); 
        } catch (SQLException e) { 
             e.printStackTrace(); 
        } 
        return rs; 
    } 
    


//关闭连接

    public static void close(Connection conn){ 
        if(conn!=null){ 
            try { 
                conn.close(); 
            } catch (SQLException e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
            } 
            conn=null; 
        } 
    } 


    public static void close(ResultSet rs){ 
        if(rs!=null){ 
            try { 
                rs.close(); 
            } catch (SQLException e) { 
                e.printStackTrace(); 
            } 
            rs=null; 
        } 
    } 
     
    public static void close(Statement stmt){ 
        if(stmt!=null){ 
            try { 
                stmt.close(); 
            } catch (SQLException e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
            } 
            stmt=null; 
        } 
    } 
  }  

本文出自 “学习园地” 博客,请务必保留此出处http://melinstudy.blog.51cto.com/8781036/1529543