阅读本文章前建议先阅读:java通过JDBC访问sqlserver数据库
一、使用原因:通过JDBC连接数据库时有时会需要连接不同的数据库,而jar包、连接url、用户名和密码等都是写定在程序中,不便修改,因此引入配置文件(key-value),可以通过key得到对应的value,即动态获取数据。
二、实现步骤
1.编写配置文件database.properties;
2.创建包com.yh.util,编写类ConfigManager,读取属性文件;
3.修改连接数据库的参数。
三、代码示例
database.properties
jdbc.SQLServerDriver.class=com.microsoft.sqlserver.jdbc.SQLServerDriver jdbc.connection.url=jdbc:sqlserver://127.0.0.1:1433;databaseName=news jdbc.connection.username=sa jdbc.connection.password=12345yehuan
ConfigManager.java
package com.yh.util; import java.io.IOException; import java.io.InputStream; import java.util.Properties; // 读取配置文件的工具类-单例模式 public class ConfigManager { private static ConfigManager configManager; private static Properties properties; private ConfigManager(){ // 把配置文件load到properties对象中 String configFile = "database.properties"; properties = new Properties();
// 获得当前类的根目录,然后在里面获得文件configFile的输入流,这样写就算项目路径变了,这里的路径也不用改,这句的相同功能代码见文末 InputStream is = ConfigManager.class.getClassLoader().getResourceAsStream(configFile); try { properties.load(is); is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static ConfigManager getInstance(){ if(configManager==null){ configManager = new ConfigManager(); } return configManager; } public String getString(String key){ return properties.getProperty(key); } }
修改后的数据库连接代码
public void getData(){ ConfigManager configManager = ConfigManager.getInstance(); String url = configManager.getString("jdbc.connection.url"); String username = configManager.getString("jdbc.connection.username"); String password = configManager.getString("jdbc.connection.password"); String driver = configManager.getString("jdbc.SQLServerDriver.class"); Connection con = null;
Statement statement = null;
ResultSet rs = null; try { // 加载驱动 Class.forName(driver); // 获得数据库连接 con = DriverManager.getConnection(url, username, password); // 执行sql语句 String sql = "select * from student"; statement = con.createStatement(); rs = statement.executeQuery(sql); while(rs.next()){ int id = rs.getInt(1); String name = rs.getString(2); int age = rs.getInt(3); System.out.println(id+" "+name+" "+age); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try {
// 释放资源
rs.close();
statement.close();
con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
相同功能代码:
坏处是项目路径变了,这里也要修改。
InputStream is = null; try { is = new FileInputStream("D:/Workspaces/MyEclipse 2017 CI/News/WebRoot/WEB-INF/classes/database.properties"); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }