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

 更新时间:2024年04月02日 08:59:23   作者:thulium_  
这篇文章主要介绍了java连接数据库的5种方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教<BR>
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

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

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

总结

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

相关文章

最新评论

?


http://www.vxiaotou.com