您的位置:首页 > 运维架构

今天新接触一个新朋友-Properties集合类

2013-09-23 19:45 302 查看
今天上jdbc实训课之前,李老师给我们介绍了一个新朋友 Properties。咋一听我还以为是一个struts.properties文件呢,结果是一个集合类,但果然和.properties是有关的。
.properties属性文件:
在里面可以定义一些字段并且为它赋值以键值对的形式存在,这将不需要我们在代码中书写,实现 了数值和代码的 分离,这样很方便我们以后修改数值。
Properties集合类作用之一:与工程中的.properties或xml文件建立联系,获取写在properties文件中 以键 值对形式存在的value值。
小例子: 获取保存在properties属性文件中的有关连接数据库信息。
先列上属性文件db.properties
#oracle
url=jdbc:oracle:thin:@localhost:1521:orcl
driver=oracle.jdbc.driver.OracleDriver
username=scott
password=tiger

#mysql
#url=jdbc:mysql://localhost:3306/test
#driver=com.mysql.jdbc.Driver
#username=root
#password=root

#sqlservers
#url=jdbc:sqlserver://localhost:1433; DatabaseName=studb
#driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#username=sa
#password=sa

java中连接数据库:

package com.strong.jdbc.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class Test {

private static String url;
private static String driver;
private static String username;
private static String password;

//静态代码块,只在程序第一次启动时,被加载一次
static{
try {
Properties prop = new Properties();
//Properties类获取属性文件中的值时要先建立文件字节流
InputStream is = new FileInputStream("db.properties");
prop.load(is);
//通过key获取value
url = prop.getProperty("url");
driver= prop.getProperty("driver");
username= prop.getProperty("username");
password = prop.getProperty("password");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

//连接数据库
public static Connection getConnection(){
Connection conn = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}

public static void main(String[] args) {
System.out.println(getConnection());
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: