1.问题描述:
jdbc获取连接的两种方式(包括properties文件方式)
额外:(两种连接都有测试)
mysql连接的jdbc:URL:jdbc:mysql://localhost:3306/数据库名(jdbc:mysql:///数据库名)
oracle连接的jdbc:URL:jdbc:oracle:thin:@localhost:1521:orcl
2.方法:
一种java.sql.Driver:
直接加载驱动,获取驱动实例,通过驱动获取连接
二种DriverManager:
通过DriverManager获取,不需要进行注册:DriverManager.registerDriver(Class.forName(mysqlDriver).newInstance());
因为在Driver中有一个静态代码块完成了DriverManager.registerDriver(new Driver());
所以直接使用反射,利用加载class文件(即加载静态代码块)来完成注册
3.代码体现:
一种方式:
public Connection getConnection(){
String url="jdbc:oracle:thin:@localhost:1521:orcl";
//用户名
String user = "scott";
//密码
String password = "tiger";
Connection connection = null;
try {
//1.加载驱动
Driver driver = (Driver)Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
//2.得到连接
Properties info = new Properties();
info.setProperty("user", user);
info.setProperty("password", password);
connection = driver.connect(url, info);
return connection;
} catch (Exception e) {
//记录日志
e.printStackTrace();
//默认业务处理
//向上抛出异常
throw new RuntimeException("找不到驱动类等等",e);
}
}
public Connection getConnection(){
String url="jdbc:oracle:thin:@localhost:1521:orcl";
//用户名
String user = "scott";
//密码
String password = "tiger";
Connection connection = null;
try {
//1.加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//2.得到连接
connection = DriverManager.getConnection(url,user,password);
return connection;
} catch (Exception e) {
//记录日志
e.printStackTrace();
//默认业务处理
//向上抛出异常
throw new RuntimeException("找不到驱动类",e);
}
}
扩展properties文件方式:
jdbc.properties:
mysqlDriver=com.mysql.jdbc.Driver
mysqlJdbcURL=jdbc:mysql://localhost:3306/demo1
muserName=root
mpassword=root
oracleDriver=oracle.jdbc.driver.OracleDriver
oracleJdbcURL=jdbc:oracle:thin:@localhost:1521:orcl
ouserName=scott
opassword=tiger
public static Connection getOracleConnection() throws Exception {
Properties properties = new Properties();
properties.load(new FileInputStream("src/jdbc.properties"));
String oracleDriver = properties.getProperty("oracleDriver");
String oracleJdbcURL = properties.getProperty("oracleJdbcURL");
String userName = properties.getProperty("ouserName");
String password = properties.getProperty("opassword");
// 1.得到驱动
Driver driver = (Driver) Class.forName(oracleDriver).newInstance();
// 2.连接
properties.put("user", userName);
properties.put("password", password);
Connection conn = driver.connect(oracleJdbcURL, properties);
return conn;
}
第二种修改为properties方式:
public static Connection getDriverManagerConnection() throws Exception {
Properties properties = new Properties();
properties.load(new FileInputStream("src/jdbc.properties"));
String mysqlDriver = properties.getProperty("mysqlDriver");
String mysqlJdbcURL = properties.getProperty("mysqlJdbcURL");
String userName = properties.getProperty("muserName");
String password = properties.getProperty("mpassword");
//注册驱动
Class.forName(mysqlDriver);
//得到连接
Connection conn = DriverManager.getConnection(mysqlJdbcURL, userName, password);
return conn;
}