将JAVA程序连接至数据库
- 下载 mysql 驱动 jar 包
- 添加入JAVA程序文件中
- 添加到 library 库中
获取数据库的五种方式
package com.ftn.jdbc.myjdbc;
//数据库的不同连接方式
import com.mysql.cj.jdbc.Driver;
import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class JdbcConn {
public static void main(String[] args) {
}
//方式一
//直接加载Driver对象,获取连接
@Test
public void connect01() throws SQLException {
Driver driver = new Driver();
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","122800");
Connection connect = driver.connect("jdbc:mysql://localhost:3306/db_03", properties);
System.out.println("第三种连接方式:" + connect);
connect.close();
}
//方式二
//使用反射加载 Driver 类,动态加载,更加灵活,减少依赖性
@Test
public void connect02() throws Exception {
Class> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver =(Driver) aClass.newInstance();
//创建 url,user和 password
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","122800");
Connection connect = driver.connect("jdbc:mysql://localhost:3306/db_03", properties);
System.out.println("第三种连接方式:" + connect);
connect.close();
}
//方式三
//使用DriverManager代替Driver进行统一管理
@Test
public void connect03() throws Exception {
//使用反射加载 Driver
Class> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//创建 url,user和 password
String url = "jdbc:mysql://localhost:3306/db_03";
String user = "root";
String password = "122800";
DriverManager.registerDriver(driver); //注册 Driver 驱动
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("第三种连接方式:" + connection);
connection.close();
}
//方式四
//使用 Class.forName 自动完成注册驱动,简化代码
@Test
public void connect04() throws Exception {
//使用反射加载 Driver
Class> aClass = Class.forName("com.mysql.cj.jdbc.Driver");
//创建 url,user和 password
String url = "jdbc:mysql://localhost:3306/db_03";
String user = "root";
String password = "122800";
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("第四种方式:" + connection);
connection.close();
}
//方式五
//在方式四基础上改进,增加配置文件,让连接 mysql 更加灵活
@Test
public void connect05() throws Exception {
//通过 Properties 对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\mysql.properties"));
//获取相关的值
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
Class> aClass = Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("第五种方式:" + connection);
connection.close();
}
}