获取数据库连接的方式
要连接数据库,需要有driver(驱动)、url(数据库地址)、username(用户名)、password(密码)。
package com.hllog;
import com.mysql.cj.jdbc.Driver;
import org.junit.Test;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class ConnectionTest {
@Test
public void testConnection1() throws SQLException {
Driver driver = new Driver();
String url = "jdbc:mysql://localhost:3306/test2";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "xxxxxx");
Connection connection = driver.connect(url, info);
System.out.println(connection);
}
// 改进:不出现第三方API,使程序具有更好的可移植性
@Test
public void testConnection2() throws Exception {
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
String url = "jdbc:mysql://localhost:3306/test2";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "xxxxxx");
Connection connection = driver.connect(url, info);
System.out.println(connection);
}
// 使用DriverManager替换Driver
@Test
public void testConnection3() throws Exception {
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
String url = "jdbc:mysql://localhost:3306/test2";
String user="root";
String password = "xxxxxx";
DriverManager.registerDriver(driver);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
// 自动注册Driver,Driver的静态代码块完成
@Test
public void testConnection4() throws Exception {
String url = "jdbc:mysql://localhost:3306/test2";
String user="root";
String password = "xxxxxx";
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
// 常用
@Test
public void testConnection5() throws Exception {
InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(is);
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");
Class clazz = Class.forName(driver);
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println(connection);
}
}
jdbc.properties文件
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/test2
username=root
password=xxxxxx
以上内容学自尚硅谷的宋红康老师的JDBC课程。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程