jdbc获取数据库连接的四种方式
方式一:
@Test
public void test01() throws SQLException {
// 创建一个数据库驱动器对象
Driver driver = new Driver();
// url地址
String url = "jdbc:mysql://localhost:3306/girls";
// 创建一个Properties对象,将账号和密码放进去
Properties pro = new Properties();
pro.setProperty("user", "root");
pro.setProperty("password", "root");
// 传参进行连接
Connection connect = driver.connect(url, pro);
System.out.println(connect);
}
方式二:
@Test
public void test02() throws Exception {
// 通过反射来实例化Driver对象
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
// url地址
String url = "jdbc:mysql://localhost:3306/girls";
// 创建一个Properties对象,将账号和密码放进去
Properties pro = new Properties();
pro.setProperty("user", "root");
pro.setProperty("password", "root");
// 传参进行连接
Connection connect = driver.connect(url, pro);
System.out.println(connect);
}
方式三:
@Test
public void test3() throws SQLException, ClassNotFoundException {
// 加载驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取链接
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/girls", "root", "root");
System.out.println(connection);
}
方式四:
1.写一个配置文件,db.properties
url = jdbc:mysql://localhost:3306/girls
username = root
password = root
classDriver = com.mysql.jdbc.Driver
@Test
public void test4() throws Exception {
// 读取配置文件
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("com/lili/db.properties");
// 加载配置文件
Properties properties = new Properties();
properties.load(in);
// 获取属性值
String url = properties.getProperty("url");
String username = properties.getProperty("username");
String classDriver = properties.getProperty("classDriver");
String password = properties.getProperty("password");
// 加载驱动
Class.forName(classDriver);
// 连接
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println(connection);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!