Java获取数据库连接

Driver:
package xuezaipiao;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.util.Properties;

public class getDabseConnection {

	public static void main(String[] args){
		
		System.out.println(getConnection());
		
	}
	private static Connection getConnection(){
		
		//1.获取本地配置文件
		
		Properties properties = new Properties();
		try {
			properties.load(new FileInputStream("D://LearnJava//learnJDBC//src//jdbc.properties"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String driverName = properties.getProperty("driver");

		//2.创建数据库驱动
		
		Driver driver = null;
		try {
			driver = (Driver) Class.forName(driverName).newInstance();//反射创建
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		//3.获取配置信息
		
		String user = properties.getProperty("user");
		String password = properties.getProperty("password");
		String jdbcUrl = properties.getProperty("jdbcUrl");
		Properties info = new Properties();
		info.put("user", user);
		info.put("password", password);
		
		//4.数据库连接
		
		Connection connection = null;
		try {
			connection = driver.connect(jdbcUrl, info);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		return connection;
	}
}


jdbc.properties

#oracle
driver=oracle.jdbc.driver.OracleDriver
jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl
user=scott
password=qiaolezi

#MySQL
#driverClass=com.mysql.jdbc.Driver
#jdbcUrl=jdbc:mysql://127.0.0.1:3306/test
#user=root
#password=qiaolezi


只需改动properties就可以获取到不同的数据库连接


对于 Oracle 数据库连接,采用如下形式: 
jdbc:oracle:thin:@localhost:1521:sid
对于 SQLServer 数据库连接,采用如下形式:
jdbc:microsoft:sqlserver//localhost:1433:sid
对于 MYSQL 数据库连接,采用如下形式:   
jdbc:mysql://localhost:3306/sid

PS:sid是数据库名

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。