已经第六天了,好快啊,今天在公司改了个需求优化的东西,只是对照着代码改啊,一头雾水,数据库底层操作都忘的差不多了,主要是之前都没理解透,发现上了这么多年学,竟然不知道怎么学习了,好像是从高中开始,就开始自带了,以为什么东西看过去就会了,然后就不会深入去理解了,最终导致了这种结果,是多么可悲的一件事啊。今天大体回忆了下JDBC数据库连接,还有好多东西不理解,明天好好看看,我决定考研了,最近好好研究研究,也不能老是闲着,李有才又不搭理我。把今天写的代码先贴上吧,明天好好悟悟价格注释。

package cn.oncelife.fordream;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 
 * @author Administrator
 *jdbc连接数据库及数据库连接池
 *1.先导入需要的驱动类以mysql为例
 */
public class Day20150407 {
    
    public static void main(String args[]){
        String sql ="select * from member";
        ResultSet rs=null;
        DBConnection db=new DBConnection();
        rs=db.query(sql);
        try {
            if(rs.next()){
                System.out.println(rs.getString(2));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

class DBConnection{
    private String JdbcDriver="com.mysql.jdbc.Driver";
    private final String url="jdbc:mysql://localhost:3306/ebaoxian";
    private final String username="root";
    private final String password="chEN123";
    private ResultSet rs=null;
    private PreparedStatement ps=null;
    private Connection conn=null;
    
    public DBConnection(){
        conn=getConnection();
    }
    public Connection getConnection(){
        try{
            Class.forName(JdbcDriver);
            conn=DriverManager.getConnection(url,username,password);
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            return conn;
        }
    }
    public ResultSet query(String sql){
        try{
            ps=conn.prepareStatement(sql);
            rs=ps.executeQuery();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            return rs;
        }
    }
    public boolean close(){
        boolean isClose=false;
        if(rs!=null){
            try{
                rs.close();
                rs=null;
                isClose=true;
            }catch(Exception e){
                isClose=false;
                e.printStackTrace();
                System.out.println("结果集关闭失败");
            }
        }
        if(ps!=null){
            try{
                ps.close();
                ps=null;
                isClose=true;
            }catch(Exception e){
                isClose=false;
                e.printStackTrace();
                System.out.println("关闭ps失败");
            }
        }
        if(conn!=null){
            try{
                conn.close();
                conn=null;
                isClose=true;
            }catch(Exception e){
                isClose=false;
                e.printStackTrace();
                System.out.println("关闭conn失败");
            }
        }
        return isClose;
    }
}

 

posted on 2015-04-07 23:50  52_it  阅读(115)  评论(0编辑  收藏  举报