Java使用JDBC连接随意类型数据库(mysql oracle。。)
生活随笔
收集整理的這篇文章主要介紹了
Java使用JDBC连接随意类型数据库(mysql oracle。。)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package cn.liz.test;import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;import org.junit.Test;public class JBDCtest {/*** 編寫一個通用的方法, 在不改動源程序的情況下, 能夠獲取不論什么數據庫的連接* 解決方式: 把數據庫驅動 Driver 實現類的全類名、url、user、password 放入一個* 配置文件里, 通過改動配置文件的方式實現和詳細的數據庫解耦. * @throws Exception */public Connection getConnection() throws Exception{String driverClass = null;String jdbcUrl = null;String user = null;String password = null;//讀取類路徑下的 jdbc.properties 文件InputStream in = getClass().getClassLoader().getResourceAsStream("jdbc.properties");Properties properties = new Properties();properties.load(in);driverClass = properties.getProperty("driver");jdbcUrl = properties.getProperty("jdbcUrl");user = properties.getProperty("user");password = properties.getProperty("password");//通過反射常見 Driver 對象. Driver driver = (Driver) Class.forName(driverClass).newInstance();Properties info = new Properties();info.put("user", user);info.put("password", password);//通過 Driver 的 connect 方法獲取數據庫連接. Connection connection = driver.connect(jdbcUrl, info);return connection;}@Testpublic void testGetConnection() throws Exception{System.out.println(getConnection());}
}<span style="white-space:pre"> </span><span style="font-family: Arial, Helvetica, sans-serif;">jdbc.properties</span>配置文件:#driver=oracle.jdbc.driver.OracleDriver
#jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl
#user=scott
#password=javadriver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/test
user=root
password=
總結
以上是生活随笔為你收集整理的Java使用JDBC连接随意类型数据库(mysql oracle。。)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringCloud-Learning
- 下一篇: 【BZOJ4821】【SDOI2017】