现有需求要在工程中链接mysql数据库和pg数据库两种
开始把我难坏了,毫无头绪,查到的结果也比较复杂,后来我自己试了下,居然可以,比较简单,分享给大家,有什么问题欢迎留言。
把pg的和mysql的配置信息区别写就ok了,然后使用不同的数据驱动(driverClass,mysql为com.mysql.jdbc.Driver,pg为org.postgresql.Driver),他们互不影响
一、在配置文件中配置pg库的链接信息,和mysql的配置区别开即可
配置文件目录:src/main/resources/application.properties
spring.gp.driver-class-name=org.postgresql.Driver
spring.gp.url = jdbc:postgresql://host:ip/database
spring.gp.username = username
spring.gp.password = password
二、添加链接pg数据库的依赖
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
三、写单测
package com.beauty.time;
import com.beauty.time.common.DataBaseUtil;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.sql.DriverManager;
/**
* @Author: lxx
* @Date: 2021/3/2 7:01 下午
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class GpTest {
@Value("${spring.gp.url}")
private String url;
@Value("${spring.gp.username}")
private String username;
@Value("${spring.gp.password}")
private String password;
static Connection connection;
@Autowired
private DataBaseUtil dataBaseUtil;
@Test
public void testPG() throws SQLException {
String sqlStr="INSERT into impair.impair_ecl(task_seq,loan_invoice_id,ecl) VALUES('lxxxxx3','xxxxxxx',5.00)";
connection = DriverManager.getConnection(url, username, password);
PreparedStatement pstmt = null;
pstmt = connection.prepareStatement(sqlStr);
pstmt.executeUpdate();
}
}