工具:eclipse(Myeclipse)
jar包:
commons-collections4-4.0.jar
commons-dbcp-1.4.jar
commons-pool-1.6.jar
Oracle 11g 11.2.0.1.0 JDBC_ojdbc6.jar
<>1.步骤:创建Properties对象
<>2.创建文件路径
<>3.加载资源配置
<>4.关闭文件路径
<>5.使用加载资源对象properties调用getProperty()方法
<>6.注册驱动
2.OverRide (覆盖,复写) Connection 中的getConnection方法
将信息返回
3.关闭连接
为何要使用到配置文件.如果某个公司本来使用是Oracle数据库,当是,不需要Oracle而是MySQL数据库
这个时候需要改源代码.,让一个不懂代码的人去改动源码是非常一件危险的事情,不建议去改动源码..而是改动配置文件..这样就能到达通用效果
就像MySQL6.0以上的版本...现在基本是免安装,,已经不再用傻瓜式安装..但是MySQL需要配置..这样就非常方便了,,减少等待时间,直接改动配置文件,,就可以用了
下面的代码是配置文件代码:
private static String driver;
private static String url;
private static String username;
private static String password;
//创建配置文件对象
static{
try{
Properties properties = new Properties();
//配置文件路徑
InputStream inStream = JDBCDemo2.class.
getClassLoader().
getResourceAsStream(
"com/csdn/jdbcdemo/date2017_11_12/propertis.txt");
//加載配製文件
properties.load(inStream);
inStream.close();
//獲取配置文件信息
//驱动器
driver = properties.getProperty("driver");
//路径
url = properties.getProperty("url");
//用户名
username = properties.getProperty("username");
//密码
password = properties.getProperty("password");
//注册驱动器
Class.forName(driver);
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println(driver);
}
//数据库连接
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection(url, username, password);
}
//关闭连接
public static void closeConnection(Connection conn){
try {
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
该代码是测试代码.查看文件是否配置成功
try {
//连接
Connection connection = JDBCDemo2.getConnection();
//DB对象
Statement state = connection.createStatement();
//SQL语句
String sql = "SELECT * FROM EMP";
//处理结果集
ResultSet rs = state.executeQuery(sql);
//遍历结果
while(rs.next()){
System.out.println(
rs.getString("ENAME")+" "+
rs.getInt("SAL")+" "+
rs.getInt("DEPTNO")+" "+
rs.getString("EMPNP")
);
}
//关闭连接
rs.close();
state.close();
JDBCDemo2.closeConnection(connection);
} catch (SQLException e) {
e.printStackTrace();
}
时间:2017年11月11日19:21:11写
修改:
第一次修改:
时间:
2017年11月12日10:25:40
修改:更新一些书写错误