JDBC 笔记与工具类

这篇博客详细介绍了Java中使用JDBC进行数据库连接的四种常见方式,包括通过Driver、DriverManager、工具类以及配置文件。此外,还展示了如何执行SQL语句(插入、更新和查询)以及处理结果集ResultSet。同时,提供了通用的数据库操作方法和资源释放的辅助工具类。
摘要由CSDN通过智能技术生成

1.JdbcTool

package jdbc1;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;


/**
 * 操作JDBC工具类,封装工具方法
 */
public class JDBCTools {
    /**
     * 关闭 ResultSet    Statement   Connection
     * @param rs
     * @param statement
     * @param conn
     */
    public static void release(ResultSet rs, Statement statement, Connection conn){
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    
    /**
     * 关闭 Statement   Connection
     * @param st
     * @param connection
     */
    public static void release(Statement st, Connection connection){
        if(st!=null){
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

    /**
     * 获取连接  通过读取配置文件从数据库服务器获取一个连接
     * @return
     */
   public static Connection getConnection() throws Exception {

       //创建Properties对象
       Properties properties = new Properties();

      //获取db.properties对应的输入流
       InputStream in = JDBCTools.class.getClassLoader().getResourceAsStream("db.properties");

       //加载对应的输入流
       properties.load(in);

       //准备数据连接的四个字符串

       //1. 数据库连接地址
       String url = properties.getProperty("url");
       //2.数据连接用户名
       String user = properties.getProperty("user");
       //3.数据库连接密码
       String password = properties.getProperty("password");
       //数据库连接驱动
       String driverClass = properties.getProperty("driverClass");

       //加载驱动
       Class.forName(driverClass);

       return   DriverManager.getConnection(url, user, password);
   }

}

2.JdbcTest

package jdbc1;

import oracle.jdbc.driver.OracleDriver;
import org.junit.Test;

import java.io.InputStream;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.Properties;

/**
 *
 */
public class JDBCTest {

    /******************************************获取数据库连接***************************************************/

    /**
     * 第一种数据库连接方式   弊端:更换数据库需要创建不同的实现类  与连接相关的参数信息
     *
     *  Driver 是一个接口:数据库厂商必须提供接口的实现,能从其中获取数据库连接
     *   可以通过Driver接口的实现类对象获取数据库连接
     *  1. 加入 mysql 驱动
     *    1). 解压 mysql-connector-java-5.1.7.zip
     *    2). 在当前项目下新建 lib 目录
     *    3). 把 mysql-connector-java-5.1.7-bin.jar 复制到 lib 目录下
     *    4). 右键 build-path , add to buildpath 加入到类路径下.s
     */
    @Test
    public void TestDriver() throws Exception {
        Driver  driver = new OracleDriver();
        Properties info = new Properties();
        String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
        info.setProperty("user","st_pay" );
        info.setProperty("password","root" );

        Connection connect = driver.connect(url, info);
        System.out.println(connect);

    }


    /**
     *
     * 第二种连接方式    优点: 利用反射与配置文件就可以实现切换不同的数据库信息就可以连接不同的数据库
     *
     * 编写一个通用的方法再不修改源程序的情况下,可以获取任何数据库的连接
     * 解决方案:把Java提供的数据库驱动Driver接口由数据库厂商实现的实现类的全类名,url,user,password放入一个配置文件
     *          通过修改配置文件的方式实现和具体的数据库解耦
     */
    @Test
    public  void testGetConnection() throws Exception {
        String driverClass="";
        String jdbcUrl="";
        String user="";
        String password="";


        //读取类路径下的db.properties文件

        Properties properties = new Properties();

        InputStream in = JDBCTest.class.getClassLoader().getResourceAsStream("db.properties");

        properties.load(in);

        jdbcUrl = properties.getProperty("url");

        driverClass = properties.getProperty("driverClass");

        user = properties.getProperty("user");

        password = properties.getProperty("password");

        //通过反射创建Driver对象
        Driver driver  = (Driver) Class.forName(driverClass).newInstance();

        Properties info = new Properties();

        info.setProperty("user", user);//接口要求key必须史user 和   password
        info.setProperty("password", password);

        //通过Driver的connect方法获取数据库连接
        Connection connect = driver.connect(jdbcUrl, info);
        System.out.println(connect);
    }

    /**
     * 第三种连接方式
     *    通过java.sql.DriverManager(是驱动的管理类)   实现数据库的连接
     *       1. 可以通过重载的getConnection()方法获取数据库连接,较为方便
     *       2. 可以同时管理多个驱动程序:若注册了多个数据库连接,则调用getConnection()方法时传入的参数不同,即返回不同的数据库连接
     */

    @Test
    public void testDriverManager() throws Exception {

        //驱动的全类名
        String driverClass="oracle.jdbc.driver.OracleDriver";

        //JDBC  url
        String url="jdbc:oracle:thin:@127.0.0.1:1521:orcl";

        //user
        String user="st_pay";

        //password
        String password="root";

        //加载数据库驱动程序(对应的Driver实现类中有注册驱动的静态代码块)
        Class.forName(driverClass);

        //通过 DriverManager的getConnection()方法获取数据库连接
        Connection connection =
                DriverManager.getConnection(url, user, password);

        System.out.println(connection);
    }

    /**
     * 第四种连接方式  
     *    整合以上连接方式 来实现通用的数据库连接
     *
     * @return
     */
    public  Connection getConnection() throws Exception {
        
        //创建Properties对象
        Properties properties = new Properties();

        //获取db.properties对应的输入流
        InputStream in = 
                JDBCTest.class.getClassLoader().getResourceAsStream("db.properties");
        
        //加载输入流
        properties.load(in);
        
        //获取数据连接信息的四个字符串
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");
        String driverClass = properties.getProperty("driverClass");


        //加载驱动  //加载数据库驱动程序(对应的 Driver 实现类中有注册驱动的静态代码块.)
        Class.forName(driverClass);

        //通过DriverManager的getConnection()方法获取数据库连接
        Connection connection = DriverManager.getConnection(url, user, password);

        System.out.println(connection);

        return  connection;
    }


    /******************************开始执行sql**********************************************/


    /**
     * Statement
     *    执行sql语句对象
     *
     *  通过JDBC向指定的数据表中插入一条记录。
     *  一
     *    1.Statement用于执行SQL语句的对象
     *    2.通过connection的createStatement()方法来获取
     *    3.通过 executeUpdate(sql) 可以执行sql语句
     *    4.传入的sql 可以时insert update delete 但不可以时select
     *  二
     *    Connection Statement都是应用程序和数据库服务器的连接资源,使用后一定要关闭
     *    需要再finally中关闭 Connection和Statement对象
     *
     *  三
     *    关闭的顺序是:先关闭后获取的。即先关闭 Statement 后关闭 Connection
     *
     *
     * @throws Exception
     */
    @Test
    public void testStatement(){
        //1.获取数据库连接
        Connection conn = null;
        //创建Sql执行对象
        Statement  statement = null;

        try{

            conn = getConnection();
            //2.准备执行的sql语句
            String sql = null;

            //插入
            //sql = "insert into customers values('3','雅典娜','984803830@qq.com',to_date('1990-12-03','yyyy-mm-dd'))";
            //修改
            //sql = "update customers set email = '384803830@qq.com' where ID=3";
            //删除
            sql = "delete from customers where id=3";
            statement = conn.createStatement();

            //执行sql
            int result= statement.executeUpdate(sql);

            System.out.println("影响行数:"+result);

        }catch(Exception e){
            e.printStackTrace();

        }finally {
            //关闭Statement 后开的先关
            try {
                if(statement!=null)
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                //关闭Connection 先开的后关
                try {
                    if(conn!=null)
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 通用的更新方法  包括insert update  delete
     */
    public int update(String sql){
        Connection conn= null;
        Statement statement = null;
        //数据库影响行数
        int result=0;

        try {
            conn= getConnection();
            statement = conn.createStatement();
            result = statement.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            JDBCTools.release(statement, conn);
        }
        return result;
    }

    @Test // 测试通用更新方法
    public void testUpdate(){
        System.out.println(update("insert into customers(id,name,email,birth)values('3','安其拉','2974434075@qq.com',to_date('1995-09-09','yyyy-mm-dd'))"));
    }


    /**
     * ResultSet:结果集,封装了使用JDBC进行查询的结果
     * 1.调用Statement的executeQuery(String sql) 可以得到结果集
     * 2.ResultSet返回的实际上就是一张数据表,有各一个指针指向数据表的第一行的前面。
     *     可以调用next()方法检测下一行是否有效,若该方法返回true,则指针下移
     *     (相当于Iterator对象的hasNext()和next()方法的结合体)
     * 3.当指针指向并定位到一行时,可以通过调用getXxx(index)和getXxx(String columnName)获取每一列的值 如: getInt(1)  getString("name")
     * 4.ResultSet当然也需要进行关闭
     *
     */
    @Test
    public  void testResultSet(){
        Connection conn = null;
        Statement statement = null;
        ResultSet rs = null;

        try {
            conn = JDBCTools.getConnection();//获取Connection数据库连接对象

            statement = conn.createStatement();//获取Statement执行sql对象

            String sql = "select id,name,email,birth from customers";//准备sql

            rs = statement.executeQuery(sql);//执行查询 得到ResultSet

            while (rs.next()){//处理ResultSet
                String ID = rs.getString(1);
                String name = rs.getString("name");
                String email = rs.getString(3);
                Date date = rs.getDate(4);
                System.out.println(ID+"--"+name+"--"+email+"--"+new SimpleDateFormat("yyyy-mm-dd HH:mm:ss").format(date));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭数据库资源
            JDBCTools.release(rs,statement ,conn );
        }

    }

}

3.db.properties

url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
user=st_pay
password=root
driverClass=oracle.jdbc.driver.OracleDriver


#driver=oracle.jdbc.driver.OracleDriver
#jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl
#user=scott
#password=java

#driver=com.mysql.jdbc.Driver
#jdbcUrl=jdbc:mysql://localhost:3306/atguigu
#user=root
#password=1230
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值