返回顶部

收藏

groovy控作sql的高级用法

更多
 def sql = Sql.newInstance("jdbc:mysql://localhost:3306/mydb",
    "user", "pswd", "com.mysql.jdbc.Driver")

// delete table if previously created
try {
   sql.execute("drop table PERSON")
} catch(Exception e){}

// create table
sql.execute('''create table PERSON (
    id integer not null primary key,
    firstname varchar(20),
    lastname varchar(20),
    location_id integer,
    location_name varchar(30)
)''')

// now let's populate the table
def people = sql.dataSet("PERSON")
people.add( firstname:"James", lastname:"Strachan", id:1, location_id:10, location_name:'London' )
people.add( firstname:"Bob", lastname:"Mcwhirter", id:2, location_id:20, location_name:'Atlanta' )
people.add( firstname:"Sam", lastname:"Pullara", id:3, location_id:30, location_name:'California' )

// do a query to check it all worked ok
def results = sql.firstRow("select firstname, lastname from PERSON where id=1").firstname
def expected = "James"
assert results == expected

// allow resultSets to be able to be changed
sql.resultSetConcurrency = java.sql.ResultSet.CONCUR_UPDATABLE

// change the data
sql.eachRow("select * from PERSON") {
    it.firstname = it.firstname * 2
}

// reset resultSetsConcurrency back to read only (no further changes required)
sql.resultSetConcurrency = java.sql.ResultSet.CONCUR_READ_ONLY

// do a query to confirm that our change actually worked
results = sql.firstRow("select firstname, lastname from PERSON where id=1").firstname
expected = "JamesJames"
assert results == expected

标签:groovy

收藏

0人收藏

支持

0

反对

0

相关聚客文章
  1. TiuVe2 发表 2018-09-04 14:15:19 按钮条件逻辑配置化的可选技术方案
  2. 炒饭 发表 2015-11-25 03:20:12 用git布署网站的方法
  3. 炒饭 发表 2015-11-25 03:20:12 用git布署网站的方法
  4. 博主 发表 2018-04-25 06:46:00 Groovy Grape
  5. 博主 发表 2018-04-26 12:23:00 Groovy Ratpack
  6. 博主 发表 2018-04-26 12:23:00 Groovy Ratpack
  7. 博主 发表 2018-04-25 06:46:00 Groovy Grape
  8. 博主 发表 2018-02-07 09:05:17 IDEA 通过数据库生成 Nutz 实体类
  9. TiuVe2 发表 2018-01-06 13:23:06 使用 yaml+groovy 实现 Java 代码可配置化
  10. 博主 发表 2015-10-02 00:00:00 精通 Groovy
  11. 炒饭 发表 2015-11-25 03:20:12 用git布署网站的方法
  12. 炒饭 发表 2015-11-25 03:20:12 用git布署网站的方法