Java读取配置文件信息连接数据库
创建java 工程,导入PGsql 驱动包结构如下:
数据库配置文件内容;
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.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.json.JSONException;
import org.json.JSONObject;
public class PGUtil {
public static final String CONFIG_FILE_LOCATION = "/db.properties"; //配置文件路径
private static Connection connection = null;
private static final Properties config = new Properties();
static {
String propertiesPath = CONFIG_FILE_LOCATION.startsWith("/") ?
CONFIG_FILE_LOCATION.substring(1) : CONFIG_FILE_LOCATION;
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try (InputStream in = classLoader.getResourceAsStream(propertiesPath)){
if (in != null){
config.load(in);
String url = config.getProperty("url");
String userName = config.getProperty("username");
String password = config.getProperty("password");
String driver = "org.postgresql.Driver";
try {
Class.forName(driver);
connection = (Connection) DriverManager.getConnection(url, userName, password);
System.out.println(connection);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
JSONObject jsonObject = new JSONObject();
String sql = "select * from users_info WHERE user_name = 'admin' AND user_password = 'admin'";
PreparedStatement pstmt;
try {
pstmt = (PreparedStatement)connection.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
try {
jsonObject.put("user_id", rs.getString("user_id"));
jsonObject.put("user_name", rs.getString("user_name"));
jsonObject.put("user_department_id", rs.getString("user_department_id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
System.out.println(jsonObject);
} catch (SQLException e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}