import java.io.FileInputStream;
|
import java.io.FileOutputStream;
|
import java.io.IOException;
|
import java.sql.Connection;
|
import java.sql.DriverManager;
|
import java.sql.SQLException;
|
import java.util.Properties;
|
|
public class ConfigHandler {
|
|
private static final String DB_PROPERTIES_FILE = "D:\\ltkjprojectconf\\config.properties";
|
private static final String DB_URL_KEY = "ip";
|
private static final String DB_PROT_KEY = "prot";
|
private static final String DB_NAME_KEY = "name";
|
private static final String DB_USER_KEY = "username";
|
private static final String DB_PASSWORD_KEY = "password";
|
private Connection connection;
|
private Connection connectToDatabase(Properties props) throws SQLException {
|
String dbUrl = "jdbc:mysql://"+props.getProperty("ip")+":"+props.getProperty("prot")+"/"+props.getProperty("name")+"" +
|
"?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8";
|
String dbUser = props.getProperty(DB_USER_KEY);
|
String dbPassword = props.getProperty(DB_PASSWORD_KEY);
|
// 加载MySQL驱动
|
try {
|
Class.forName("com.mysql.cj.jdbc.Driver");
|
} catch (ClassNotFoundException e) {
|
e.printStackTrace();
|
}
|
if (connection == null || connection.isClosed()) {
|
// 关闭旧的连接
|
if (connection != null) {
|
try {
|
connection.close();
|
} catch (SQLException e) {
|
e.printStackTrace();
|
}
|
}
|
// 创建新的数据库连接
|
// connection = DriverManager.getConnection(connectionString, username, password);
|
}
|
return DriverManager.getConnection(dbUrl, dbUser, dbPassword);
|
}
|
|
public void modifyConfigAndRefreshDB(String newDbUrl,String prot,String name, String newDbUser, String newDbPassword) throws IOException, SQLException {
|
Properties properties = new Properties();
|
properties.load(new FileInputStream(DB_PROPERTIES_FILE));
|
|
// 修改配置
|
properties.setProperty(DB_URL_KEY, newDbUrl);
|
properties.setProperty(DB_PROT_KEY, prot);
|
properties.setProperty(DB_NAME_KEY, name);
|
properties.setProperty(DB_USER_KEY, newDbUser);
|
properties.setProperty(DB_PASSWORD_KEY, newDbPassword);
|
|
// 更新配置文件
|
properties.store(new FileOutputStream(DB_PROPERTIES_FILE), null);
|
|
// 关闭旧的数据库连接,并建立新的连接
|
Connection connection = connectToDatabase(properties);
|
// ... 使用新的connection进行数据库操作 ...
|
|
// 确保关闭数据库连接
|
if (connection != null && !connection.isClosed()) {
|
connection.close();
|
}
|
}
|
|
public static void main(String[] args) {
|
ConfigHandler configHandler = new ConfigHandler();
|
try {
|
// 假设新的数据库连接信息
|
String newDbUrl = "192.168.0.5";
|
String prot = "3306";
|
String name = "ltkjpeis1";
|
String newDbUser = "root";
|
String newDbPassword = "root";
|
|
configHandler.modifyConfigAndRefreshDB(newDbUrl,prot,name,newDbUser, newDbPassword);
|
System.out.println("数据库配置已更新并且数据库连接已刷新。");
|
} catch (IOException | SQLException e) {
|
e.printStackTrace();
|
}
|
}
|
}
|