package com.jdbc;
import java.io.IOException;
/**
* 1,通过Driver数据库的两种链接方法
*/
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Driver;
public class JDBCTest00_Driver {
//Driver第一种:耦合度太高
public static void testDriver() throws SQLException {
//1,创建一个Driver实现类的对象;
Driver driver=new Driver();
//2,准备链接数据库的基本信息:url user password;
String url="jdbc:mysql://localhost:3306/testjdbc";
Properties info=new Properties();
info.put("user","root");
info.put("password","cchaos");
//3,调用Driver 接口的connect(url,info)获取数据库连接;
Connection conn=(Connection) driver.connect(url, info);
System.out.println(conn);
}
//Driver第二种:通用方法
public Connection getConnection() throws Exception {
String driverClass=null;
String jdbcURL=null;
String user=null;
String password=null;
//读取类路径下的properties 文件
/**Properties类:
* /* //jdbc.properties
driver=com.mysql.jdbc.Driver
jdbcURL=jdbc:mysql://localhost:3306/testjdbc
user=root
password=cchaos */
* Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,
* 各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱
* 离程序本身去修改相关的变量设置。像Python支持的配置文件是.ini文件,同样,它也有自己读取配置文件的类ConfigParse,
* 方便程序员或用户通过该类的方法来修改.ini配置文件。在Java中,其配置文件常为.properties文件,格式为文本文件,
* 文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。
* 它提供了几个主要的方法:
1. getProperty ( String key),用指定的键在此属性列表中搜索属性。也就是通过参数 key ,得到 key 所对应的 value。
2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件
(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。
3. setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
4. store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,
将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。
5. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。
*/
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");
//通过反射获取类的方法
@SuppressWarnings("deprecation")
Driver driver=(Driver)Class.forName(driverClass).newInstance();//选取数据库对应的方法
Properties info=new Properties();
info.put("user", user);
info.put("password", password);
Connection conn=(Connection) driver.connect(jdbcURL, info);
return conn;
}
public static void main(String[] args) throws Exception {
// testDriver();
JDBCTest00_Driver jt=new JDBCTest00_Driver();
System.out.println(jt.getConnection());
}
}
JDBC中Driver方法链接数据库
最新推荐文章于 2024-04-10 15:56:55 发布