gpt4 book ai didi

sql - Grails:创建动态 SQL 连接

转载 作者:行者123 更新时间:2023-12-01 08:30:16 25 4
gpt4 key购买 nike

对于我的应用程序,我需要在运行时进行动态数据库连接。我知道,有很多方法可以创建多个数据源,但我认为它们并不是动态的。场景:

用户可以输入数据库凭据并连接到远程数据库以将单个行和表导入其他数据库。为此,我需要动态连接到远程数据库。

我已经尝试在服务中做到这一点,就像他们在 If I use groovy sql class in grails, does it use the grails connection pooling? 中所说的那样。

注意:在这种情况下 GORM 是可有可无的,我可以使用纯 SQL 代替。

有什么想法吗?谢谢。。

编辑:Grails 2.3.4

最佳答案

您可以通过这种方式在运行时注册 DataSource bean:

给定一个 Grails 服务:

package whatever

import groovy.sql.Sql
import org.springframework.context.*
import org.apache.tomcat.jdbc.pool.DataSource
import org.springframework.context.support.GenericApplicationContext

class DataSourceService implements ApplicationContextAware {

ApplicationContext applicationContext

def registerBean( String beanName, String dsurl, String uid, String pwd ) {
if( !applicationContext.containsBean( beanName ) ) {
def bb = new grails.spring.BeanBuilder()
bb.beans {
"$beanName"( DataSource ) {
driverClassName = "com.mysql.jdbc.Driver"
url = dsurl
username = uid
password = pwd
validationQuery = "SELECT 1"
testOnBorrow = true
maxActive = 1
maxIdle = 1
minIdle = 1
initialSize = 1
}
}
bb.registerBeans( applicationContext )
log.info "Added $beanName"
}
else {
log.error "Already got a bean called $beanName"
}
}

def deRegisterBean( String beanName ) {
if( applicationContext.containsBean( beanName ) ) {
(applicationContext as GenericApplicationContext).removeBeanDefinition( beanName )
log.info "Removed $beanName"
}
else {
log.error "Trying to deRegister a bean $beanName that I don't know about"
}
}

def getSql( String beanName ) {
Sql.newInstance( applicationContext.getBean( beanName ) )
}
}

然后,您应该可以调用该服务来注册一个新的数据源:

dataSourceService.registerBean( 'myDS', 'jdbc:mysql://localhost:3306/mysql', 'test', 'test' )

为它获取一个 Groovy Sql 对象:

dataSourceService.getSql( 'myDS' ).rows( 'SELECT * FROM whatever' )

完成后移除 bean

dataSourceService.deRegisterBean( 'myDS' )

手指交叉...我从我的一个项目中提取了该代码并对其进行了更改/未测试;-)

更新

runtime-datasources已创建插件,该插件使用本文中概述的方法允许在运行时添加/删除数据源。

关于sql - Grails:创建动态 SQL 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20634276/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com