JDBC 获取数据库连接
2021/7/18 2:06:09
本文主要是介绍JDBC 获取数据库连接,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
如下
package com.jdbc.connection; import org.junit.Test; import java.io.InputStream; import java.sql.Connection; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class ConnectionTest { //方式一 @Test public void testConnection1() throws SQLException { Driver driver = new com.mysql.jdbc.Driver();//获取Driver的实现类对象 String url = "jdbc:mysql://localhost:3306/bookdb"; Properties info = new Properties(); info.setProperty("user","root"); info.setProperty("password",""); Connection conn = driver.connect(url, info); System.out.println(conn); } //方式二:对方式一迭代 @Test public void testConnection2() throws Exception { //获取Driver的实现类对象(使用反射) Class clazz = Class.forName("com.mysql.jdbc.Driver()"); Driver driver = (Driver) clazz.newInstance(); //要链接的数据库 String url = "jdbc:mysql://localhost:3306/bookdb"; //获取需要的用户名和密码 Properties info = new Properties(); info.setProperty("user","root"); info.setProperty("password",""); //获取连接 Connection conn = driver.connect(url, info); System.out.println(conn); } //方式三:使用DriverManager替代Driver @Test public void testConnection3() throws Exception { //获取Driver的实现类对象(使用反射) Class clazz = Class.forName("com.mysql.jdbc.Driver()"); Driver driver = (Driver) clazz.newInstance(); //提供连接的基本信息 String url = "jdbc:mysql://localhost:3306/bookdb"; String user = "root"; String password = ""; //注册驱动 DriverManager.registerDriver(driver); //获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn); } @Test public void testConnection4() throws Exception { //提供连接的基本信息 String url = "jdbc:mysql://localhost:3306/bookdb"; String user = "root"; String password = ""; //加载Driver Class.forName("com.mysql.jdbc.Driver()"); //获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn); System.out.println(conn); } //方式五:将数据库连接需要的4个基本信息声明在配置文件中 @Test public void testConnection5() throws Exception { //1.获取配置文件中4个基本信息 InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties pros = new Properties(); pros.load(is); String user = pros.getProperty("user"); String password = pros.getProperty("password"); String url = pros.getProperty("url"); String driverClass = pros.getProperty("driverClass"); //2.加载驱动 Class.forName(driverClass); //3.获取连接 Connection conn = DriverManager.getConnection(url, user, password); System.out.println(conn); } }
这篇关于JDBC 获取数据库连接的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-20获取apk的md5值有哪些方法?-icode9专业技术文章分享
- 2024-11-20xml报文没有传 IdentCode ,为什么正常解析没报错呢?-icode9专业技术文章分享
- 2024-11-20如何知道代码有没有进行 Schema 验证?-icode9专业技术文章分享
- 2024-11-20Mycat教程:新手快速入门指南
- 2024-11-20WebSocket入门:轻松掌握WebSocket基础
- 2024-11-19WebSocket入门指南:轻松搭建实时通信应用
- 2024-11-19Nacos安装资料详解:新手入门教程
- 2024-11-19Nacos安装资料:新手入门教程
- 2024-11-19升级 Gerrit 时有哪些注意事项?-icode9专业技术文章分享
- 2024-11-19pnpm是什么?-icode9专业技术文章分享