groovy 速学 - 30 - Sql
来源:互联网 发布:Java仿hashmap实现 编辑:程序博客网 时间:2024/05/17 01:03
目录
- Sql
- 概述
- Sql类
- 建立 Sql 对象
- 执行语句
- 建表
- Insert
- Update
- Delete
- Query
- DataSet 类
- OR Mapping
- 概述
- 简单的 OR Mapping 实现
- Sql
摘要
执行Sql,dataSet,OR mapping
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))")
Insert
def toy = new Toy(toyName: "toy1", unitPrice: 100)sql.execute("insert into toys values(${toy.toyName}, ${toy.unitPrice})")
Update
sql.execute("update toys set unitPrice=? where toyName=?", [200, toy.toyName])
Delete
sql.execute("delete from toys")
Query
sql.eachRow("select * from toys where unitPrice>?", [100]) { t -> println t.toyName + ":" + t.unitPrice}
DataSet 类
DataSet 类是 Sql 类的子类,通过 DataSet 可以不写 Sql 语句直接对数据库进行操作
//建立DataSet对象,参数为表名def toys = sql.dataSet("toys")//Querydef list = toys.rows()list.each { t -> println t.toyName + ":" + t.unitPrice}//Inserttoys.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 Mappingdef q = new SqlQuery() { @Override def mapRow(Object row) { return new Toy(toyName: row["toyName"], unitPrice: row["unitPrice"]) }}q.sql = sqlq.query = "select * from toys"Toy[] toys = q.execute()
0 0
- groovy 速学 - 30 - Sql
- groovy 速学 - 03 - 脚本
- groovy 速学 - 07 - 异常
- groovy 速学 - 09 - 集合
- groovy 速学 - 10 - 映射
- groovy 速学 - 11 - 类
- groovy 速学 - 19 - 正则
- groovy 速学 - 22 - IO
- groovy 速学 - 01 - 安装与运行
- groovy 速学 - 04 - 操作符
- groovy 速学 - 24 - 与 Java 互调
- groovy 速学 - 31 - Builder 与 Template
- groovy 速学 - 32 - Web 开发
- groovy 速学 - 02 - 数据类型与作用域
- groovy 速学 - 05 - 方法,函数与闭包
- groovy 速学 - 06 - 流程控制与范围
- groovy 速学 - 23 - Xml及 Json 的处理
- Groovy SQL 分页组件
- zoj 1745 Are We There Yet?
- 360校园招聘2015届技术类笔试题
- 关于tomcat启动web时classloader加载el实现类报错的解决方式
- QT中PRO文件写法的详细介绍
- 第四周 项目三 用对象数组操作长方柱类
- groovy 速学 - 30 - Sql
- 内核层读写应用层文件,使用filp_open函数。
- AOJ 593分组玩游戏:利用STL 快速排序
- [算法] Alpha-Beta搜索
- 商人过河问题(DFS)
- Linux常用命令大全
- android基础学习之sqlite
- js判断字符串开头和分割
- 腾讯笔试 求基因碱基的逆序数