Groovy之旅系列之六(Groovy Sql)
這是一篇關(guān)于Groovy Sql的文章.如果你沒(méi)jdbc的基礎(chǔ)也沒(méi)有關(guān)系.
它是一門(mén)新的語(yǔ)言,可以在string里面包含變量 .
假設(shè)你的數(shù)據(jù)庫(kù)有person表,這里用的是SqlServer2000,字段有id,username,password,age.
來(lái)看看我們的第一個(gè)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}"
}
);
第一句是導(dǎo)入相應(yīng)的包,這和Java沒(méi)什么區(qū)別.
第二句根據(jù)所傳入的url,username,password,jdbc driver.得到一個(gè)Sql 對(duì)象.
然后根據(jù)這個(gè)sql對(duì)象進(jìn)行查詢,具體操作可以去查看groovy api.
沒(méi)想到groovy到數(shù)據(jù)庫(kù)的操作竟是如此簡(jiǎn)單,太強(qiáng)了.
我們?cè)賮?lái)看看它的firstRow方法:
讓我們來(lái)試試再?gòu)?fù)雜一些的數(shù)據(jù)庫(kù)操作吧.
往數(shù)據(jù)庫(kù)插入一條記錄的多種寫(xiě)法:
修改或刪除數(shù)據(jù)庫(kù)記錄:
Groovy對(duì)數(shù)據(jù)庫(kù)的操作就是如此簡(jiǎn)單,現(xiàn)在就讓我們?nèi)ジ惺芩镊攘Π桑?br />
它是一門(mén)新的語(yǔ)言,可以在string里面包含變量 .
num = 3
println("There is a ${num}");
println("There is a ${22/7}")
println("There is a " + num)
正如你所看到的,在${}里面的東西,groovy都會(huì)把它解釋成groovy expressions.println("There is a ${num}");
println("There is a ${22/7}")
println("There is a " + num)
假設(shè)你的數(shù)據(jù)庫(kù)有person表,這里用的是SqlServer2000,字段有id,username,password,age.
來(lái)看看我們的第一個(gè)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}"
}
);
第二句根據(jù)所傳入的url,username,password,jdbc driver.得到一個(gè)Sql 對(duì)象.
然后根據(jù)這個(gè)sql對(duì)象進(jìn)行查詢,具體操作可以去查看groovy api.
沒(méi)想到groovy到數(shù)據(jù)庫(kù)的操作竟是如此簡(jiǎn)單,太強(qiáng)了.
我們?cè)賮?lái)看看它的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}";
讓我們來(lái)試試再?gòu)?fù)雜一些的數(shù)據(jù)庫(kù)操作吧.
往數(shù)據(jù)庫(kù)插入一條記錄的多種寫(xiě)法:
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]);
修改或刪除數(shù)據(jù)庫(kù)記錄:
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對(duì)數(shù)據(jù)庫(kù)的操作就是如此簡(jiǎn)單,現(xiàn)在就讓我們?nèi)ジ惺芩镊攘Π桑?br />
posted on 2008-05-13 13:29 々上善若水々 閱讀(5425) 評(píng)論(1) 編輯 收藏