JDBC获取连接

JDBC介绍

JDBC获取连接_第1张图片

(1)JDBC 是一个规范定义的接口;
(2)JDBC接口由各大数据库厂商实现:MySQL,SqlServer,Oracle,DB2等,他们会编写自家数据库的驱动来实现这个接口;
(3)我们只要调用JDBC的方法即可,不用管具体的实现;

连接步骤

(1)导入java.sql包:项目上新建lib目录,把驱动程序放到目录下,Add as libraay;
(2)把驱动加载到内存: Class.forName(“com.mysql.cj.jdbc.Driver”),此驱动类存在静态代码块,在类加载时候执行,注册驱动;

static{
     
       try {
     
            DriverManager.registerDriver(new Driver()); //注册数据库驱动
           } catch (SQLException var1) {
     
            throw new RuntimeException("Can't register driver!");
           }
     }

(3)定义数据库的链接地址

 url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT";

JDBC获取连接_第2张图片

(4)得到与数据库的连接对象

  Connection connection = DriverManager.getConnection(url, "root", "root");

连接方式

连接方式一

public static void main(String[] args) throws Exception {
     
        Properties properties = new Properties();
        String url="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT";
        properties.setProperty("user","root");
        properties.setProperty("password","123456");
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn= DriverManager.getConnection(url,properties);
        System.out.println(conn);
    }

连接方式二

JDBC获取连接_第3张图片

public class test2 {
     
    public static void main(String[] args) throws Exception {
     
        ClassLoader classLoader = test2.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("db.properties");

        Properties properties = new Properties();
        properties.load(is);

        String driver = properties.getProperty("driver");
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String password = properties.getProperty("password");

        Class.forName(driver);
        Connection conn= DriverManager.getConnection(url,user,password);
        System.out.println(conn);
    }
}

你可能感兴趣的:(JDBC)