springboot项目简单的实现操作多数据库源
//可以定义工具类方便使用 import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; @Slf4j @Component public class ResultSetToUtil {
//连接信息可以从配置文件里获取,方便修改 private static String url; private static String userName; private static String password; @Value("${on-line.url}") public void setUrl(String url){ this.url = url; } @Value("${on-line.password}") public void setPassword(String password){ this.password = password; } @Value("${on-line.name}") public void setUserName(String userName){ this.userName = userName; } public static UserEntity ResultSetToDepStaff(String id){ UserEntity userEntity = new UserEntity();//定义的实体类 String sql = " SELECT id as id, name as name FROM user where id = "+ id ; log.info("=========查询sql为:{}",sql); try {
//放到try可以自动释放流,因为他们继承了AutoCLoseable接口 try (Connection currentConnection = DriverManager.getConnection(url, userName, password)) { try (Statement countStatement = currentConnection.createStatement()) { try (ResultSet countResultSet = countStatement.executeQuery(sql)) { if (countResultSet.next()) { userEntity.setId(Long.parseLong(countResultSet.getString("id"))); userEntity.setName(countResultSet.getString("name")); } } } } }catch (Exception e){ log.error("异常:",e); } return userEntity; } }
数据库连接信息可以放到配置文件里
以上就能满足查询其他数据库的数据啦。
如果嫌继承多数据源麻烦,就可以使用这种简单快捷的方式。具体细节也可以自行百度的哈