当我们使用不同的数据库管理系统的时候,例如Mysql和Oracle。因为这两个系统在加载驱动时不同,或者说如果你打算用写好的MySQL语句去调用Oracle需要更改代码中的加载驱动项、用户名、密码等,十分的不变,所有我们可以将数据库信息写在配置文件中,让程序通过读取配置文件来获得这些信息。
配置文件
是一种属性文件,后缀名是.properties(键值对)
步骤
首先我们需要建立一个properties文件,把我们上文提到的相关信息填写到文件中,当我们需要更换时只需要在这个文件中改变即可
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.136.100:3306/MySchool
user=root
pwd=ok
然后建立一个读取数据库属性文件,获取数据库连接信息的类:
public class Prop {
private static Properties p = new Properties();
//param 需要调用属性
public static String getp(String param) {
try {
//读取文件
p.load(new FileInputStream("resource/db.properties"));
} catch (IOException e) {
e.printStackTrace();
}
//根据param读出对应的值
return p.getProperty(param);
}
}
接着建立JDBC方法:
通过设置属性,调用Prop方法来获取properties文件的内容,方便了以后更换所带来的不必要麻烦。提高效率
public class PstDao {
private static String driver= Prop.getp("driver");
private static String url = Prop.getp("url");
private static String user = Prop.getp("user");
private static String pwd = Prop.getp("pwd");
public static Connection getConn() {
try {
Class.forName(driver);
return DriverManager.getConnection(url, user, pwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static ResultSet query(String sql, Object... params) {
Connection conn = getConn();
PreparedStatement pst = null;
ResultSet rs = null;
try {
pst = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
pst.setObject(i + 1, params[i]);
}
rs = pst.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
测试:
@Test
public void query() throws SQLException {
String sql = "select SubjectName,score from subject s left join result on\n" +
"sub_no=subjectNo where score>? and subjectName in(?,?)";
ResultSet rs = PstDao.query(sql,60,"高等数学-1","高等数学-2");
while (rs.next()) {
System.out.print(rs.getString("SubjectName")+"----");
System.out.println(rs.getInt("score"));
}
rs.close();
}