package com.hxzkappboot.config; import com.alibaba.druid.pool.DruidDataSource; import javax.sql.DataSource; import com.hxzkappboot.util.R; import com.hxzkappboot.util.StatusCode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.sql.Connection; import java.sql.SQLException; @Service public class DynamicDataSourceService { @Autowired private DataSource dataSource; public R changeDatabaseUrl(String newUrl, String username, String password) throws SQLException { R response ; if (!(dataSource instanceof DruidDataSource)) { throw new IllegalArgumentException("DataSource is not an instance of DruidDataSource"); } DruidDataSource druidDataSource = (DruidDataSource) dataSource; // 构造新的数据库连接URL String url = "jdbc:mysql://" + newUrl + ":3306/hxzkuwb?characterEncoding=UTF8"; // 尝试使用新的数据库连接信息获取连接 try { druidDataSource.setUrl(url); druidDataSource.setUsername(username); druidDataSource.setPassword(password); try (Connection connection = druidDataSource.getConnection()) { // 如果能够成功获取连接,则继续重新初始化连接池 System.out.println("Successfully connected to the database with the new URL."); } catch (SQLException e) { // 如果获取连接失败,则抛出异常 response = new R(StatusCode.Fail); response.setData("连接失败"); // throw new SQLException("Failed to connect to the database with the new URL", e); } // 重新初始化连接池 druidDataSource.restart(); druidDataSource.init(); response = new R(StatusCode.Success); response.setData("连接成功"); } catch (Exception e) { // 处理其他可能的异常 response = new R(StatusCode.Fail); response.setData("连接失败"); // throw new SQLException("Error while changing database URL", e); } return response; } }