groovy 速学 - 30 - Sql
发布时间:2020-12-14 16:47:51 所属栏目:大数据 来源:网络整理
导读:目录 Sql 概述 Sql类 建立 Sql 对象 执行语句 建表 Insert Update Delete Query DataSet 类 OR Mapping 概述 简单的 OR Mapping 实现 摘要 执行Sql,dataSet,OR mapping Sql 概述 在 Groovy 中,资源管理的负担由 Groovy 本身负责,所以不用关闭 connection
目录
摘要
Sql概述在 Groovy 中,资源管理的负担由 Groovy 本身负责,所以不用关闭 connection,也不用关闭 ResultSet。 Sql类建立 Sql 对象def db = "jdbc:mysql://localhost:3306/groovy?useUnicode=true&characterEncoding=UTF-8"
def username = "root"
def password = "root"
def driver = "com.mysql.jdbc.Driver"
Sql sql = Sql.newInstance(db,username,null,driver)
执行语句建表sql.execute("create table if not exists toys(toyName varchar(40),unitPrice int(8))")
Insertdef toy = new Toy(toyName: "toy1",unitPrice: 100)
sql.execute("insert into toys values(${toy.toyName},${toy.unitPrice})")
Updatesql.execute("update toys set unitPrice=? where toyName=?",[200,toy.toyName])
Deletesql.execute("delete from toys")
Querysql.eachRow("select * from toys where unitPrice>?",[100]) { t ->
println t.toyName + ":" + t.unitPrice
}
DataSet 类DataSet 类是 Sql 类的子类,通过 DataSet 可以不写 Sql 语句直接对数据库进行操作 //建立DataSet对象,参数为表名
def toys = sql.dataSet("toys")
//Query
def list = toys.rows()
list.each { t ->
println t.toyName + ":" + t.unitPrice
}
//Insert
toys.add(toyName: "toy999",unitPrice: 999)
OR Mapping概述数据库与程序天生存在阻抗不匹配的问题,即程序中是数据的存储形式是对象,数据库中的存储形式是二维表。为解决这一问题,可以使用对象关系映射模型。 简单的 OR Mapping 实现abstract class SqlQuery {
def sql
def query
def abstract mapRow(row) //delay the implement
def execute() {
def rowsList = sql.rows(query)
def results = []
def size = rowsList.size()
0.upto(size - 1) { i ->
results << this.mapRow(rowsList[i])
}
return results
}
}
// 实现抽象类 SqlQuery 来达到 OR Mapping
def q = new SqlQuery() {
@Override
def mapRow(Object row) {
return new Toy(toyName: row["toyName"],unitPrice: row["unitPrice"])
}
}
q.sql = sql
q.query = "select * from toys"
Toy[] toys = q.execute()
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |