今天上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());

}

}