連接數據庫,並查詢第一條數據
Connecting to MySQL using Groovy - Stack Overflow
@GrabConfig(systemClassLoader=true) @Grab('mysql:mysql-connector-java:8.0.21') import java.sql.*; import groovy.sql.Sql def connectionString = "jdbc:mysql://<ip-address>:<port-number>/<database>" // jdbc:mysql://localhost/db?useUnicode=true&characterEncoding=UTF-8' // def username = "<username>" def password = "<password>" def driver = "com.mysql.jdbc.Driver" def sqlInstance = Sql.newInstance(connectionString, username, password, driver) // 查詢第一條數據 def firstRow = sqlInstance.firstRow("select * from <database>.<table>") print firstRow
指定連接使用 UTF-8 編碼
How to set up MySQL on Windows to accept UTF-8 data via Groovy JDBC connections - Stack Overflow
jdbc:mysql://localhost/db?useUnicode=true&characterEncoding=UTF-8'
使用 Prepared Statement 語法
Sql (Groovy 2.5.4)
mysql - Insert multiple rows in one SQL statement in Groovy - Stack Overflow
解決數據轉義、注入問題,代碼如下:
def params = [10, 'Groovy', 'http://groovy.codehaus.org'] sql.execute('insert into PROJECT (id, name, url) values (?, ?, ?)', params)
插入多條數據:
def updateCounts = sql.withBatch('insert into TABLENAME(a, b, c) values (?, ?, ?)') { ps -> ps.addBatch([1, 2, 3]) ps.addBatch([10, 20, 30]) ps.addBatch(100, 200, 300) // 或者使用循環 }
如果不想處理數據庫連接關閉
The Apache Groovy programming language - Working with a relational database
Sql.withInstance(url, user, password, driver) { sql -> // use 'sql' instance ... // i.e. sql.execute("sql statement") }
相關鏈接
Groovy - Database - Tutorialspoint
Interacting with a SQL database
常見錯誤匯總
No suitable driver found for XXXXXXX
jdbc - No suitable driver found when connected to mysql in groovy - Stack Overflow
Dependency management with Grape
GrabConfig (Groovy 3.0.5)
在連接數據庫時,產生如下錯誤:
Caught: java.sql.SQLException: No suitable driver found for jdbc:mysql://<ip-address>:<port-number>/<database> java.sql.SQLException: No suitable driver found for jdbc:mysql://<ip-address>:<port-number>/<database> at demo.run(demo.groovy:6)
由於 JDBC 驅動的加載方式,在使用 JDBC 驅動前,需要 配置 Grape 將 JDBC 驅動依賴 附加到 系統類加載器,即代碼:
@GrabConfig(systemClassLoader=true) // Set to true if you want to use the system classloader when loading the grape. // This is normally only required when a core Java class needs to reference the // grabbed classes, e.g. for a database driver accessed using DriverManager.
或者在命令行中將 Jar 加入 ClassPath 中:
groovyconsole -cp mysql-connector-java-5.1.27-bin.jar
參考文獻
K4NZ / 連接數據庫(使用 MySQL 演示)
The Apache Groovy programming language - Working with a relational database