问题描述
在 Groovy 中,我们需要连接 SQLite 数据库,以进行某些简单的数据存取操作。
该笔记将记录:在 Groovy 中,如何连接数据库。
解决方案
我们依旧使用 JDBC 连接数据库,所以与 Java 的用法是类似的(存在的问题也多半相仿),只是函数调用不同。
@Grapes([
@Grab(group='org.xerial',module='sqlite-jdbc',version='3.7.2'),
@GrabConfig(systemClassLoader=true)
])
import java.sql.*
import org.sqlite.SQLite
import groovy.sql.Sql
def sql = Sql.newInstance("jdbc:sqlite:/path/to/sample.db", "org.sqlite.JDBC")
// 创建表
sql.execute("drop table if exists person")
sql.execute("create table person (id integer, name string)")
def people = sql.dataSet("person")
people.add(id:1, name:"leo")
people.add(id:2,name:'yui')
sql.eachRow("select * from person") {
println("id=${it.id}, name= ${it.name}")
}
参考文献
Use Groovy language JDBC with SQLite database – T. C. Mits 108