数据库连接的步骤

来源:互联网 发布:类似淘宝千里眼的插件 编辑:程序博客网 时间:2024/04/28 10:17
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;



/*数据库连接的步骤
 * 1.注册驱动 (Driver)
2.    建立连接(创建Connection)
3.    创建执行sql语句(通常是创建Statement或者其子类)
4.    执行语句
5.    处理执行结果(在非查询语句中,该步骤是可以省略的)
6.    释放相关资源

 * */
public class Oracle {
    //加载驱动
    static{
        try {
            Class.forName(Config.getConfig().getProperty("driver"));
        } catch (ClassNotFoundException e) {
            
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    //获取连接
    public Connection getCon(){
        Connection con=null;
        try {
            con=DriverManager.getConnection(Config.getConfig().getProperty("url"),Config.getConfig().getProperty("username"), Config.getConfig().getProperty("password"));
        } catch (SQLException e) {
        
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return con;
    }
    //执行语句  使用执行句柄
    public void zhiX(){
        Connection con=getCon();
        Statement stmt=null;
        ResultSet rs=null;
        //创建执行句柄
        try {
            stmt=con.createStatement();
            rs=stmt.executeQuery("select * from user");
            while(rs.next()){
                System.out.println("id:"+rs.getInt(1)+"\tname:"+rs.getString(2)+"\tbirthday:"+rs.getDate(3)+"\tmoney:"+rs.getFloat(4));
            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            //释放资源
            try {
                rs.close();
                stmt.close();
                con.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            
        }
    }
    
    

}
class Config extends Properties {

    /**
     * .
     */
    private static final long serialVersionUID = 8652043360181690630L;
    private static Config config=new Config();
    private Config(){
        try {
            load(Config.class.getClassLoader().getResourceAsStream("db.properties"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static Config getConfig(){
        if(config==null){
            config=new Config();
        }
        return config;
    }

}
0 0
原创粉丝点击