使用intellij idea 连接oracle数据库
1.首先添加oracleDriver驱动jar
在E:\oracle\product\10.2.0\db_1\jdbc\lib目录下;
2.加载驱动,获取连接
配置文件jdbc.properties信息:
driver=oracle.jdbc.driver.OracleDriver
jdbcUrl=jdbc:oracle:thin:@localhost:1521:orcl
user=scott
password=zq123456
package com.zq.jdbc;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Properties;
public class Main {
public static void main(String[] args) {
try {
new Demo().test();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Demo{
public void test() throws Exception{
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties=new Properties();
properties.load(resourceAsStream);
String driver = properties.getProperty("driver");
String jdbcUrl = properties.getProperty("jdbcUrl");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
//注册驱动程序;可以同时注册多个驱动程序,当getconnection时,传入不同的参数可以得到不同的数据库连接;
DriverManager.registerDriver((Driver) Class.forName(driver).newInstance());
//连接数据库;
Connection connection = DriverManager.getConnection(jdbcUrl, user, password);
System.out.print(connection);
}
public void connectDb() throws Exception{
InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties=new Properties();
properties.load(resourceAsStream);
String driver = properties.getProperty("driver");
String jdbcUrl = properties.getProperty("jdbcUrl");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
Driver driverObject = (Driver) Class.forName(driver).newInstance();
Properties info=new Properties();
info.put("user",user);
info.put("password",password);
Connection connect = driverObject.connect(jdbcUrl, info);
System.out.print(connect);
}
}