import java.sql.Connection;
import java.util.Properties;
import com.mysql.jdbc.Driver;
public class JDBCDriver_getConnection {
//通过Driver接口获取连接,实际开发基本不用
public static void main(String[] args) throws Exception {
new JDBCDriver_getConnection().getConnection();
}
public Connection getConnection() throws Exception{
//连接参数
String driverClass = null;
String url=null;
String user = null;
String password = null;
Properties properties = new Properties();//使用Properties
properties.load(getClass().getClassLoader().getResourceAsStream("jdbc.properties"));//读取配置文本
//参数变量赋值
user = properties.getProperty("user");
password = properties.getProperty("password");
url = properties.getProperty("url");
driverClass = properties.getProperty("driverClass");
//配置connect()的 Properties
Properties info = new Properties();
info.put("user", user);
info.put("password", password);
Driver driver = (Driver) Class.forName(driverClass).newInstance();//注入驱动
Connection connection = (Connection) driver.connect(url, info);//获取连接
return connection;
/*
* 以下是jdbc.properties 配置文件内容,配置文件需放在src根目录下
*
driverClass = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3307/Test
user = root
password = 3306
*/
}
}