当前位置: 代码网 > it编程>编程语言>Java > java连接数据库的5种方式解读

java连接数据库的5种方式解读

2024年05月15日 Java 我要评论
方式一:直接导入第三方库驱动类这种加载方式在jdbc入门时已经用过,这个driver属于第三方库,。为静态加载,灵活性差,依赖性抢方式二:使用反射机制获取方式一和方式二代码package com.hs

方式一:直接导入第三方库驱动类

这种加载方式在jdbc入门时已经用过,这个driver属于第三方库,。为静态加载,灵活性差,依赖性抢

方式二:使用反射机制获取

方式一和方式二代码

package com.hsp.edu;
 
 import com.mysql.cj.jdbc.driver;
 
 import java.lang.reflect.constructor;
 import java.lang.reflect.invocationtargetexception;
 import java.sql.connection;
 import java.sql.sqlexception;
 import java.util.properties;
 
//java获取连接的5种方式
public class jdbcconnect {
    public static void main(string[] args) throws sqlexception, classnotfoundexception, instantiationexception, illegalaccessexception, nosuchmethodexception, invocationtargetexception {
        connect01();
        connect02();
 
    }
    //方式一,直接导入第三方库驱动类
    public static void connect01() throws sqlexception {
 
        //获取驱动
        driver driver = new driver();
        //获取连接
        string url = "jdbc:mysql://localhost:3306/jdbc?servertimezone=utc&usessl=false&useser" +
                "verprepstmts=true&characterencoding=utf-8&usessl=false";
        //将用户名和密码放入到properities对象中
        properties properties = new properties();
        properties.setproperty("user","root");//用户
        properties.setproperty("password","888888");//密码
        final connection connect = driver.connect(url, properties);
        system.out.println(connect);
    }
    //方式二:使用反射加载driver:动态加载,更加的灵活,减少依赖
    public static void connect02() throws classnotfoundexception, instantiationexception, illegalaccessexception, sqlexception, nosuchmethodexception, invocationtargetexception {
        //获取driver类的字节码文件对象
        final class<?> clazz = class.forname("com.mysql.cj.jdbc.driver");
        //注意:在用字节码文件对象获取driver对象时,直接newinstance被idea提示已经弃用
        final constructor<?> constructor = clazz.getdeclaredconstructor();
        final driver driver = (driver)constructor.newinstance();
        string url = "jdbc:mysql://localhost:3306/jdbc?servertimezone=utc&usessl=false&useser" +
                "verprepstmts=true&characterencoding=utf-8&usessl=false";
        //将用户名和密码放入到properities对象中
        properties properties = new properties();
        properties.setproperty("user","root");//用户
        properties.setproperty("password","888888");//密码
        final connection connect = driver.connect(url, properties);
        system.out.println(connect);
 
    }
}
 

方式三:使用drivermanager类

//方式三:使用drivermanager替换driver
    public static void connect03() throws sqlexception, invocationtargetexception, instantiationexception, illegalaccessexception, nosuchmethodexception, classnotfoundexception {
        //drivermanager类支持更好的获取连接的方法,可以直接将用户和密码作为参数,而不用存储到properities
        final class<?> clazz = class.forname("com.mysql.cj.jdbc.driver");
        final constructor<?> constructor = clazz.getdeclaredconstructor();
        final driver driver =(driver)constructor.newinstance();
        //创建url和user和password
        string url = "jdbc:mysql://localhost:3306/jdbc?servertimezone=utc&usessl=false&useser" +
                "verprepstmts=true&characterencoding=utf-8&usessl=false";
        string user = "root";
        final string password = "888888";
      drivermanager.registerdriver(driver);//注册driver驱动
        final connection connection = drivermanager.getconnection(url, user, password);
        system.out.println(connection);
 
    }

方式四:在加载driver类时自动完成驱动注册(以此简化代码)

driver类的底层源码 

静态代码块:在类加载的时候会执行一次 

从上面的driver类的源码可以看出,在加载driver类的时候,其静态代码块,已经完成了驱动的注册

//方式四:加载driver时自动完成注册(这种方式使用的最多,推荐使用)
    public static void connect04() throws classnotfoundexception, sqlexception {
        //使用反射加载了driver类
        //在加载 driver类时,完成注册
        class.forname("com.mysql.cj.jdbc.driver");
        string url = "jdbc:mysql://localhost:3306/jdbc?servertimezone=utc&usessl=false&useser" +
                "verprepstmts=true&characterencoding=utf-8&usessl=false";
        string user = "root";
        string password="888888";
        final connection connection = drivermanager.getconnection(url, user, password);
        system.out.println(connection);
 
    }

方式五:将信息写入到配置文件

一个疑问:为什么不写`class.forname("com.mysql.cj.jdbc.driver");也可以获取到连接?

在驱动文件中meta-inf下面的services有个com.mysql.cj.jdbc.driver文件里面已经记录了加载的全类名。

我们的程序将会直接按照文件中的内容进行加载

使用配置文件,当我们需要修改的时候就不用修改代码,只用修改配置文件即可

解惑:properties类和properties文件没有直接关系(以前认为如果创建了一个properies文件,就已经存在了一个properties对象)

properties类只是和properties文件存储的格式一样(以键值对的形式存储),但是在使用的时候还是需要将文件中的数据读取到程序中 配置文件目录

//方式五:进一步优化,将信息写入到配置文件
    public static void connect05() throws ioexception, classnotfoundexception, sqlexception {
        //通过properties对象获取配置文件信息
        properties properties = new properties();
        properties.load(new fileinputstream("src\\mysql.properties"));//此时已经将配置文件的信息读取到了properties中
        //获取相关信息
        final string user = properties.getproperty("user");//用户
        final string password = properties.getproperty("password");//密码
        final string url = properties.getproperty("url");//url
        final string driver = properties.getproperty("driver");
         class.forname(driver);//注册驱动
        final connection connection = drivermanager.getconnection(url, user, password);//获取连接
        system.out.println(connection);
 
 
    }

课堂练习

属性文件

package com.hsp;
 
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.ioexception;
import java.sql.connection;
import java.sql.drivermanager;
import java.sql.sqlexception;
import java.sql.statement;
import java.util.properties;
 
/*
参考老师代码,使用方式5完成
1.创建news表
2.使用jdbc添加5条记录
3.修改id=1的记录content改成一个新的记录
 */
public class jdbc02 {
    public static void main(string[] args) throws ioexception, classnotfoundexception, sqlexception {
        //前置工作:获取配置文件中的信息
        properties properties = new properties();
        properties.load(new fileinputstream("src\\mysql1.properties"));//读取信息到集合中
        final string driver = properties.getproperty("driver");//获取全类名
        final string url = properties.getproperty("url");//获取url
        final string user = properties.getproperty("user");//获取用户名
        final string password = properties.getproperty("password");//获取密码
        system.out.println(properties);
        //1.注册驱动
      class.forname(driver);
        //2.获取连接
        final connection connection = drivermanager.getconnection(url, user, password);
 
        //3.执行 sql语句
       //string sql1 = "create table news(id int,content varchar(32))";
       string sql2="insert into news values (1,'居民健康'),(2,'商品健康'),(3,'大熊猫')";
       string sql3="update news set content='湖北'where id=1;";
        final statement statement = connection.createstatement();
        //final int row1 = statement.executeupdate(sql1);//返回影响的行数
        final int row2 = statement.executeupdate(sql2);//返回影响的行数
        final int row3 = statement.executeupdate(sql3);
 
        //:验证是否执行成功
        /*if(row1!=0){
            system.out.println("执行成功");
 
        }else {
            system.out.println("执行失败");
        }*/
        if (row2!=0){
            system.out.println("执行成功");
        }else {
            system.out.println("执行失败");
        }
        if(row3!=0){
            system.out.println("执行成功");
        }else {
            system.out.println("执行失败");
        }
 
        //4.关闭资源
        statement.close();
        connection.close();
    }
}
 

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。 

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com