我是 Grails 的新手,我有疑问。假设我将 Datasource.groovy
配置为 mysql
数据库。一切正常,我的 grails 应用程序正在运行。
在 Controller 中,如果我想添加/修改我在 DataSource.groovy
中设置的数据库,我该怎么做?
同样,我需要在每个 Controller 中做这样的事情:
def db = Sql.newInstance(
'jdbc:mysql://*****',
'root',
'',
'com.mysql.jdbc.Driver'
)
为了获取我指向 DataSource.groovy
文件的数据库实例?
这样做有什么最佳做法吗?
最佳答案
你应该能够做到这一点(我建议这是在服务而不是 Controller 中完成的,因为它会让你的 Controller 更干净,你的代码更容易理解)
import groovy.sql.Sql
class DataSourceAccessingService {
def datasource
def runSomeQuery( String sql ) {
def sql = new Sql( datasource )
...
}
}
关于java - 如何在 grails 中获取数据库实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11357147/