Java作為一門面向?qū)ο蟮木幊陶Z言,在處理數(shù)據(jù)時需要讀取配置文件和數(shù)據(jù)庫,以滿足程序運(yùn)行的需求。
讀取配置文件主要使用Java API提供的Properties類,它是Hashtable類的一個子類,可以讀取鍵值對的屬性文件,并且可以很方便地根據(jù)鍵名獲取對應(yīng)的屬性值。具體代碼如下:
import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; public class ConfigReader { public static void main(String[] args) throws IOException { Properties properties = new Properties(); FileInputStream input = new FileInputStream("config.properties"); properties.load(input); String url = properties.getProperty("db.url"); String username = properties.getProperty("db.username"); String password = properties.getProperty("db.password"); System.out.println("url = " + url); System.out.println("username = " + username); System.out.println("password = " + password); } }
上述代碼中,我們通過創(chuàng)建Properties對象,然后讀取配置文件config.properties,將其關(guān)聯(lián)到Properties對象中,再通過getProperty方法根據(jù)鍵名獲取對應(yīng)的屬性值。可以根據(jù)具體需要設(shè)置不同的鍵值,例如數(shù)據(jù)庫的連接地址、用戶名和密碼。
讀取數(shù)據(jù)庫使用Java API提供的JDBC(Java Database Connectivity),使用JDBC中的Connection對象連接數(shù)據(jù)庫,使用Statement對象執(zhí)行SQL語句,ResultSet對象裝載并返回數(shù)據(jù)庫查詢結(jié)果。具體代碼如下:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class DBReader { public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456"); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("select * from user"); while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); System.out.println("id = " + id + ", name = " + name + ", age = " + age); } resultSet.close(); statement.close(); connection.close(); } }
上述代碼中,我們首先加載MySQL數(shù)據(jù)庫的驅(qū)動類com.mysql.jdbc.Driver,然后通過getConnection方法連接數(shù)據(jù)庫,獲取Connection對象。接著使用Connection對象創(chuàng)建Statement和ResultSet對象,通過executeQuery方法執(zhí)行查詢語句,并將結(jié)果集遍歷獲取查詢結(jié)果。最后需要關(guān)閉ResultSet、Statement、Connection對象,釋放資源。