配置文件一般以.properties为后缀名,例如下面的例子的db.properties

这里的话是要注意等号的左右俩边是不能有空格的
第一种方法
使用的话ResourceBundle类中有一个方法ResourceBundle.getBundle( )是得到配置文件内容的
package cn.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ResourceBundle;
public class JDBCUtils {
private static String driver;
private static String url;
private static String username;
private static String password;
static {
ResourceBundle bundle = ResourceBundle.getBundle("db");
driver = bundle.getString("driver");
url = bundle.getString("url");
username = bundle.getString("username");
password= bundle.getString("password");
}
public Connection getConnection()
{
Connection conn =null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public void Close(Connection conn,PreparedStatement pstmt ,ResultSet rs)
{
try {
if(rs!=null) {
rs.close();
}
if(pstmt!=null)
{
pstmt.close();
}
if(conn!=null)
{
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
这里的静态代码块static{ }在类被加载之前就会执行
第二种方法
package cn.jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
public class JDBCUtils2 {
private static String driver;
private static String url;
private static String username;
private static String password;
static {
try {
//利用classloader来加载properties
//获得当前对象的类加载器
ClassLoader loader = JDBCUtils2.class.getClassLoader();
//通过类加载器获得配置文件的输入流
InputStream is = loader.getResourceAsStream("db.properties");
//获得配置文件properties对象
Properties p = new Properties();
//获取输入流
p.load(is);
driver = p.getProperty("driver");
url = p.getProperty("url");
username = p.getProperty("username");
password = p.getProperty("password");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Connection getConnection()
{
Connection conn =null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,username,password);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public void Close(Connection conn,PreparedStatement pstmt ,ResultSet rs)
{
try {
if(rs!=null) {
rs.close();
}
if(pstmt!=null)
{
pstmt.close();
}
if(conn!=null)
{
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
ps:第一种方式所书写的配置文件只需要写名称,而第二种方式是要将配置文件的全名写入(包括后缀名)
本文介绍了两种在Java中读取数据库配置文件的方法:使用ResourceBundle类的getBundle方法和使用Properties类加载配置文件。详细展示了如何在静态代码块中初始化数据库连接参数,并提供了JDBC连接的示例代码。
1万+

被折叠的 条评论
为什么被折叠?



