一、創建數據庫
(略),運行sql腳本即可、查詢結果:
二、連接到數據庫
注意:該處采用IntelliJ IDEA進行代碼編寫因此,步驟較原書多一點。
1、添加com.mysql.jdbc.Driver
將mysql-connector-java-5.1.7-bin.jar添加到lib下;將jar包右鍵add as library添加為庫。結構如下圖所示:
2、代碼編寫
sql=Sql.newInstance('jdbc:mysql://localhost:3306/weatherinfo','root','root',
'com.mysql.jdbc.Driver')
println sql.connection.catalog
3、結果顯示:
weatherinfo
三、數據庫的select操作
代碼編寫:
println'city :temperature'
sql.eachRow('SELECT*FROM weather;'){
println"${it[0]}:${it[1]}"http://也可以是it.city等
}
結果展示:
city :temperature
Beijing :30
Tianjin :31
Guiyang :26
Shanghai :35
Guangzhou :39
Dalian :30
四、將數據轉換成XML表示
代碼編寫:
def builder=new MarkupBuilder()
builder.weather{
sql.eachRow('SELECT * FROM weather;'){
city(name:it.city,temperature:it.temperature)
}
}
結果展示:
五、使用DataSet
使用Groovy的dataSet方法接收一個表名,返回一個DataSet實例,它作為一個虛擬代理,直到迭代時,才會去取出實際的行。例子:
代碼調用:
println 'cities with higher temperature:'
def dataSet=sql.dataSet('weather')
def citiesWithHigherTemperature=dataSet.findAll{it.temperature>30}
citiesWithHigherTemperature.each{
println "${it[0]}:${it[1]}"
}
結果展示:
cities with higher temperature:
Tianjin:31
Shanghai:35
Guangzhou:39
六、插入與更新
我們可以使用兩種方法來添加數據到數據庫
1、使用DataSet
代碼編寫
println "number of cities before insert is${sql.rows('SELECT*FROM weather;').size()}"
dataSet.add(city:'Harbin ',temperature:10)
println "number of cities after insert is${sql.rows('SELECT*FROM weather;').size()}"
結果展示
number of cities before insert is 6
number of cities after insert is 7
2、使用sql類的execute方法或者executeInsert方法
代碼編寫
println "number of cities before insert is${sql.rows('SELECT*FROM weather;').size()}"
sql.execute("INSERT INTO weather(city, temperature) VALUES ('Shenzhen',39);")
println "number of cities after insert is${sql.rows('SELECT*FROM weather;').size()}"
結果展示
number of cities before insert is 8
number of cities after insert is 9
七、訪問Microsoft Excel
groovy中可以用Sql類來訪問Excel電子表格。由于JDK1.8已經刪除ODBC相關功能,此處不再研究。若您有更好的解決辦法,聯系我
代碼編寫:
def sql=Sql.newInstance(
"""jdbc.odbc.Driver = {Microsoft Excel Driver (*.xls,*.xlsx,*.xlsm,*.xlsb)};
DBQ = ../temperature.xls;
READONLY = false""",'','')
println"../temperature.xls"
sql.eachRow('SELECT*from [temperature$]'){
println "${it.city}:${it.temperature}"
}
異常展示:
Caught: java.sql.SQLException: No suitable driver found for jdbc.odbc.Driver = {Microsoft Excel Driver (*.xls,*.xlsx,*.xlsm,*.xlsb)};
DBQ = ../temperature.xls;
READONLY = false
java.sql.SQLException: No suitable driver found for jdbc.odbc.Driver = {Microsoft Excel Driver (*.xls,*.xlsx,*.xlsm,*.xlsb)};
DBQ = ../temperature.xls;
READONLY = false
at ExcelConnection.run(ExcelConnection.groovy:9)
《完》