fei.wang
2025-04-18 321a74059773cfecc01d6313f7c2e2d45545d6d3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
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;
    }
}