JDBC从入门到实现

1 篇文章 0 订阅
1 篇文章 0 订阅
本文详细介绍了Java JDBC的概念和操作步骤,包括注册驱动、获取连接、执行SQL语句和处理结果集。同时,讨论了JDBC的功能,如DriverManager、Connection、Statement和ResultSet。此外,还提到了三层架构在项目中的应用以及URL指定字符集的重要性。文章还简述了动态代理的必要条件,并对比了C3P0和Druid两种开源连接池的使用方法。
摘要由CSDN通过智能技术生成

jdbc的概念
    是一种用于执行sql语句的Java API;  就是为了帮助开发人员快速实现与数据库的连接
jdbc操作步骤
    1.导入Java包
    2.注册驱动  : Class from(写Java包driver的地址)
    3.获取连接   :  Drivermanager.getConnection(数据库地址,账号及密码) 有返回值
    4. 获取执行者对象   :  用第3步调用createstatement
    5.执行sql语句并接受返回结果   :(1)string字符串拼接你想要执行的sql语句    ; (2)在调用第4步的结果.executeQuery(将sql存入进去) 
    6.处理结果   :while循环(第5步第2个方法调用.next()); 然后在打印结果调用get方法
    7.释放资源


public class Test1 {
    public static void main(String[] args) throws Exception{
        //注册驱动
        Class.forName("com.mysql.jdbc.Driver");

        //获取连接
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db04", "root", "root");

        //获取执行者对象
        Statement sta = connection.createStatement();

        //执行sql语句 并且接受结果
        String sql="select * from user";
        ResultSet set = sta.executeQuery(sql);

         //处理结果
        while (set.next()){
            System.out.println(set.getInt("id") + "\t" + set.getString("name"));

        }
        //释放资源
        set.close();
        sta.close();
        connection.close();
    }


}


jdbc各个功能
    DriverManager   : 驱动管理对象,告诉程序该使用哪一个数据库驱动 
    Connection  :  数据库连接对象 ;管理对象:- 开启事务:setAutoCommit(boolean autoCommit);     参数为false,则开启事务。 -- (改为手动提交)
 提交事务:commit();
 回滚事务:rollback();
    Statement   : 用来执行sql语句的对象   ; 参数sql 可以执行select语句
    ResultSet   :  结果集对象
jdbc工具类
    配置文件(在src下创建config.properties) 固定格式

//固定格式
driverClass=com.mysql.jdbc.Driver

//url=jdbc:mysql(固定格式);localhost也可以写自己本机的IP地址;
//3306代表自己端口号;aa是想连接哪个数据库名

url=jdbc:mysql://localhost:3306/aa

//用户名(创建数据库时的用户名)
username=root

//密码(创建数据库时的密码)
password=root


三层架构
     在idea创建项目时 需要采用分包思想
    基本上分为  : 控制层(servlet);业务层(service) 数据持久层(dao) ; 然后用于存储学生      类,用户类的(domain)包 
 执行流程
        先由浏览器发送请求到控制层,然后在返回给业务层,在返回给数据持久层,最后在返回给数据库执行sql ;最后数据库在将结果从后往前走响应给浏览器
url指定字符集
    当执行sql语句到数据库中 有些中文就会出现乱码的情况,这时候就需要来指定字符集
        url=jdbc:mysql://localhost:3306/你的库?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT

动态代理

必要条件
    必须有接口
    抽象角色  -- 接口
    真实角色  --  需要被增强的目标类
    代理角色  -- proxy创建的对象

public class Test {
    public static void main(String[] args) {
        //真实对象
        Student stu=new Student();

        //创建代理对象
        StudentInterface stuproxy= (StudentInterface) Proxy.newProxyInstance(
                stu.getClass().getClassLoader(),  //获取类加载器
                stu.getClass().getInterfaces(), //实现一个数组接口
                //以上两步都是固定格式
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                      //只是增强eat方法 其他方法照样调用
                        System.out.println("---此次调用的方法名:"+method.getName());
                        if ("eat".equals(method.getName())){
                            System.out.println("---hello world---");
                        }else {
                            //其他方法 调用真实对象,照样输出
                            method.invoke(stu,args);
                        }
                        return null;
                    }
                }
        );

开源连接池
    C3P0
        1.先要配置文件c3p0-config.xml  (必须在src下)
        2. 导入Java包
        3.创建c3p0连接池对象   : new CombopooledDataSource()
        4.获取数据库连接进行使用  : 用第3步调用getConnection()
        5.执行sql语句并接受返回结果   :(1)string字符串拼接你想要执行的sql语句    ; (2)在调用第4步的结果.executeQuery(将sql存入进去)  ;(3) 调用(2)executeQuery 执行查询
        6.处理结果   :while循环(第5步第2个方法调用.next()); 然后在打印结果调用get方法
        7.释放资源

public class C3P0Test {
    public static void main(String[] args) throws SQLException {
    //创建c3p0的数据库连接池对象
     DataSource dataSource = new ComboPooledDataSource();

     //通过连接池对象获取数据库连接
        Connection con = dataSource.getConnection();

        //执行操作
        //定义一个sql语句
        String sql="select * from student";
        //把sql语句存入,获取执行者对象
        PreparedStatement pst = con.prepareStatement(sql);

        //执行查询
        ResultSet rs = pst.executeQuery();


        //循环只遍历一次,获取所有值
        while (rs.next()){
            System.out.println(rs.getInt("sid") + "\t" + rs.getString("name")+ "\t" + rs.getInt("age")+ "\t" + rs.getDate("birthday"));

        }
        //释放资源
        rs.close();
        pst.close();
        con.close();
    }

    }


    Druid
        1.先要配置文件(必须在src下)
        2. 导入Java包
        3.通过properties集合加载配置文件          InputStream is = DruidDemo1.class.getClassLoader().getResourceAsStream("druid.properties");  将配置文件存入字符流中
        Properties prop = new Properties();通过properties集合,加载配置文件
        prop.load(is);
        4.通过Druid连接池工厂类获取数据库连接池对象  : DruidDataSourceFactory.createDataSource(prop);
        5.获取数据库连接,进行使用  :  Connection con = dataSource.getConnection();
        6.执行sql语句并接受返回结果   :(1)string字符串拼接你想要执行的sql语句    ; (2)在调用第4步的结果.executeQuery(将sql存入进去)  ;(3) 调用(2)executeQuery 执行查询
        7.处理结果   :while循环(第5步第2个方法调用.next()); 然后在打印结果调用get方法
        8.释放资源

<c3p0-config>
  <!-- 使用默认的配置读取连接池对象 -->
  <default-config>
  	<!--  连接参数 -->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/db14</property>
    <property name="user">root</property>
    <property name="password">root</property>
    
    <!-- 连接池参数 -->
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">10</property>
    <property name="checkoutTimeout">3000</property>
  </default-config>

  <named-config name="otherc3p0"> 
    <!--  连接参数 -->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/db15</property>
    <property name="user">root</property>
    <property name="password">root</property>
    
    <!-- 连接池参数 -->
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">8</property>
    <property name="checkoutTimeout">1000</property>
  </named-config>
</c3p0-config>
public class DruidTest {
    public static void main(String[] args) throws Exception {
        //获取配置文件得流对象
        InputStream is = DruidTest.class.getClassLoader().getResourceAsStream("druid.properties");

        //通过properties集合,加载配置文件
        Properties prop = new Properties();
         prop.load(is);

        //通过druid连接池工厂类获取数据库连接池对象
        DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);


        //通过连接池对象获取数据库连接进行使用
        Connection con = dataSource.getConnection();

        //定义一个sql语句
        String sql="select * from student";

        //把sql语句存入,获取执行者对象
        PreparedStatement pst = con.prepareStatement(sql);

        //执行查询
        ResultSet rs = pst.executeQuery();


        //循环只遍历一次,获取所有值
        while (rs.next()){
            System.out.println(rs.getInt("sid") + "\t" + rs.getString("name")+ "\t" + rs.getInt("age")+ "\t" + rs.getDate("birthday"));

        }
        //释放资源
        rs.close();
        pst.close();
        con.close();

以上两个方式基本大同小异,使用一个就行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值