java连接数据库的5种方式解读_java_脚本之家

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

 更新时间:2024年04月02日 08:59:23   作者:thulium_  
这篇文章主要介绍了java连接数据库的5种方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教<BR>

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

这种加载方式在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();
    }
}
 

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。 

相关文章

  • javaWeb使用Kaptcha组件生成验证码

    javaWeb使用Kaptcha组件生成验证码

    这篇文章主要为大家详细介绍了javaWeb使用Kaptcha组件生成验证码的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-10-10
  • java 抽象类与接口的区别介绍

    java 抽象类与接口的区别介绍

    这篇文章主要介绍了java 抽象类与接口的区别介绍的相关资料,需要的朋友可以参考下
    2016-10-10
  • java 多线程-锁详解及示例代码

    java 多线程-锁详解及示例代码

    本文主要介绍 Java 多线程锁的基础知识,这里整理了相关资料及示例代码有兴趣的小伙伴可以参考下
    2016-09-09
  • Mybatis中单双引号引发的惨案及解决

    Mybatis中单双引号引发的惨案及解决

    这篇文章主要介绍了Mybatis中单双引号引发的惨案及解决方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-01-01
  • 使用SpringBoot中整合Redis

    使用SpringBoot中整合Redis

    这篇文章主要介绍了使用SpringBoot中整合Redis,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-06-06
  • 使用java实现http多线程断点下载文件(一)

    使用java实现http多线程断点下载文件(一)

    Java 多线程断点下载文件基本原理:利用URLConnection获取要下载文件的长度、头部等相关信息,并设置响应的头部信息,本文将详细介绍,需要了解更多的朋友可以参考下
    2012-12-12
  • Springboot自定义mvc组件如何实现

    Springboot自定义mvc组件如何实现

    这篇文章主要介绍了Springboot自定义mvc组件如何实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • Java模拟扑克牌洗牌实现生成52张扑克的方法示例

    Java模拟扑克牌洗牌实现生成52张扑克的方法示例

    这篇文章主要介绍了Java模拟扑克牌洗牌实现生成52张扑克的方法,涉及Java数组遍历、重排及输出等相关操作技巧,需要的朋友可以参考下
    2018-01-01
  • Mybatis-Plus中的查询指定字段

    Mybatis-Plus中的查询指定字段

    在使用Mybatis-Plus进行数据查询时,可以通过指定字段来优化查询效率,方法一和方法二分别执行不同的SQL语句,其中方法二在执行时通常会更高效,因为它可能通过减少数据处理量和优化查询结构来提升性能,比较两种方法的SQL执行情况
    2024-09-09
  • JAVA中使用双括号来初始化静态常量的小技巧

    JAVA中使用双括号来初始化静态常量的小技巧

    这篇文章主要介绍了JAVA中使用双括号来初始化静态常量的小技巧,需要的朋友可以参考下
    2014-06-06

最新评论