groovy 速学 - 30 - Sql

来源:互联网 发布:Java仿hashmap实现 编辑:程序博客网 时间:2024/05/17 01:03

目录

    • Sql
      • 概述
      • Sql类
        • 建立 Sql 对象
        • 执行语句
          • 建表
          • Insert
          • Update
          • Delete
          • Query
      • DataSet 类
      • OR Mapping
        • 概述
        • 简单的 OR Mapping 实现

摘要

执行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
原创粉丝点击