package com.roy.dynamicDs;

import com.roy.routingDs.config.DynamicDataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author roy
 * @date 2022/3/3
 * @desc
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class DSTest {

    @Resource
    DataSource dataSource;

    @Test
    public void changeDataSource(){
        //设置数据源的路由关键字  == 这个路由关键字就可以由前端传进来，实现数据源动态切换。
//        DynamicDataSource.name.set("DS1");
        DynamicDataSource.name.set("DS2");

        String sql = "select * from course";
        try {
            Connection connection = dataSource.getConnection();
            Statement statement = connection.createStatement();
            if(statement.execute(sql)){
                ResultSet rs = statement.getResultSet();
                while(rs.next()){
                    long cid = rs.getLong("cid");
                    String cname = rs.getString("cname");
                    System.out.println("cid => "+cid + "; cname => cname");
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

    }

}
