这是一篇关于Groovy Sql的文章.如果你没jdbc的基础也没有关系.
它是一门新的语言,可以在string里面包含变量 .
假设你的数据库有person表,这里用的是SqlServer2000,字段有id,username,password,age.
来看看我们的第一个Groovy Sql:
import groovy.sql.Sql;
sql = Sql.newInstance("jdbc:jtds:sqlserver: // localhost / pubs","sa","","net.sourceforge.jtds.jdbc.Driver");
sql.eachRow(" select * from person",
{
println it.id + " -- ${it.username} -- ${it.password} -- ${it.age}"
}
); 第一句是导入相应的包,这和Java没什么区别.
第二句根据所传入的url,username,password,jdbc driver.得到一个Sql 对象.
然后根据这个sql对象进行查询,具体操作可以去查看groovy api.
没想到groovy到数据库的操作竟是如此简单,太强了.
我们再来看看它的firstRow方法:
让我们来试试再复杂一些的数据库操作吧.
往数据库插入一条记录的多种写法:
修改或删除数据库记录:
Groovy对数据库的操作就是如此简单,现在就让我们去感受他的魅力吧.
它是一门新的语言,可以在string里面包含变量 .
num
=
3
println( " There is a ${num} " );
println( " There is a ${22/7} " )
println( " There is a " + num)
正如你所看到的,在${}里面的东西,groovy都会把它解释成groovy expressions.
println( " There is a ${num} " );
println( " There is a ${22/7} " )
println( " There is a " + num)
假设你的数据库有person表,这里用的是SqlServer2000,字段有id,username,password,age.
来看看我们的第一个Groovy Sql:
import groovy.sql.Sql;
sql = Sql.newInstance("jdbc:jtds:sqlserver: // localhost / pubs","sa","","net.sourceforge.jtds.jdbc.Driver");
sql.eachRow(" select * from person",
{
println it.id + " -- ${it.username} -- ${it.password} -- ${it.age}"
}
);
第二句根据所传入的url,username,password,jdbc driver.得到一个Sql 对象.
然后根据这个sql对象进行查询,具体操作可以去查看groovy api.
没想到groovy到数据库的操作竟是如此简单,太强了.
我们再来看看它的firstRow方法:
row
=
sql.firstRow("
select
username,password
from
person");
println "Row: username = ${row.username} and password = ${row.password}";
println "Row: username = ${row.username} and password = ${row.password}";
让我们来试试再复杂一些的数据库操作吧.
往数据库插入一条记录的多种写法:
username
=
"cc"
password = "gg"
sql. execute (" insert into person (username, password) values (${username}, ${password})")
sql. execute (" insert into person values ( ' admin ' , ' admin ' , 99 )");
sql. execute (" insert into person (username,password) values (? , ?)", [ username,password ] );
password = "gg"
sql. execute (" insert into person (username, password) values (${username}, ${password})")
sql. execute (" insert into person values ( ' admin ' , ' admin ' , 99 )");
sql. execute (" insert into person (username,password) values (? , ?)", [ username,password ] );
修改或删除数据库记录:
id
=
1
;
sql. execute (" update person set username = ' dddd ' where id = ?", [ id ] );
sql. execute (" delete from person where id = ?", [ 2 ] )
sql. execute (" update person set username = ' dddd ' where id = ?", [ id ] );
sql. execute (" delete from person where id = ?", [ 2 ] )
Groovy对数据库的操作就是如此简单,现在就让我们去感受他的魅力吧.