Groovy连接2个数据库进行数据操作
时间: 2023-07-26 07:21:24 浏览: 94
在Groovy中连接多个数据库进行数据操作,可以使用不同的数据库驱动程序和连接池。以下是一个示例代码,演示如何连接两个数据库(MySQL和Oracle)并执行数据操作:
```groovy
@Grab(group='org.codehaus.groovy.modules', module='groovy-sql', version='3.0.0')
import groovy.sql.Sql
import groovy.sql.SqlDataSource
// MySQL 数据库连接信息
def mysqlUrl = 'jdbc:mysql://localhost:3306/mydb'
def mysqlUsername = 'root'
def mysqlPassword = 'root'
// Oracle 数据库连接信息
def oracleUrl = 'jdbc:oracle:thin:@localhost:1521:xe'
def oracleUsername = 'system'
def oraclePassword = 'oracle'
// 创建 MySQL 数据库连接池和 Sql 对象
def mysqlDataSource = new SqlDataSource(
url: mysqlUrl,
username: mysqlUsername,
password: mysqlPassword,
driver: 'com.mysql.jdbc.Driver'
)
def mysql = Sql.newInstance(mysqlDataSource)
// 创建 Oracle 数据库连接池和 Sql 对象
def oracleDataSource = new SqlDataSource(
url: oracleUrl,
username: oracleUsername,
password: oraclePassword,
driver: 'oracle.jdbc.driver.OracleDriver'
)
def oracle = Sql.newInstance(oracleDataSource)
// 在 MySQL 中插入数据
mysql.execute("INSERT INTO users (username, password) VALUES ('john', 'doe')")
// 在 Oracle 中查询数据
def result = oracle.rows("SELECT * FROM orders WHERE customer_id = 123")
// 关闭连接
mysql.close()
oracle.close()
```
在上面的示例中,我们使用了 `groovy-sql` 模块来连接数据库和执行数据操作。我们首先定义了两个数据库的连接信息(URL、用户名、密码和驱动程序),然后创建了两个 `SqlDataSource` 对象,分别用于连接 MySQL 和 Oracle 数据库。接着,我们使用 `Sql.newInstance` 方法来创建两个 `Sql` 对象,用于执行数据操作。最后,我们在 MySQL 数据库中插入了一条数据,然后在 Oracle 数据库中查询了一些数据。最后,我们使用 `close` 方法关闭了连接。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)