Groovy中能否像Java一样为PreparedStatement指定数据类型?
Absolutely! Since Groovy is built on top of Java and fully interoperable with it, you can use PreparedStatement exactly the same way as you do in Java—including explicitly specifying data types for parameters, just like your Java example.
1. Directly using Java's PreparedStatement in Groovy
You can write code that's nearly identical to your Java snippet. Groovy doesn't restrict you from using standard JDBC classes and methods:
// Get your database connection (same as Java) def connection = DriverManager.getConnection("jdbc:your_db_url", "username", "password") def sqlStatement = "INSERT INTO your_table (date_column) VALUES (?)" PreparedStatement ps = connection.prepareStatement(sqlStatement) // Specify java.sql.Date type explicitly, just like Java def utilDate = new Date() // This is java.util.Date ps.setDate(1, new java.sql.Date(utilDate.getTime())) ps.executeUpdate() // Don't forget to clean up resources ps.close() connection.close()
Note: Just like in Java, you need to make sure you're using java.sql.Date (not the default java.util.Date Groovy imports) when calling setDate()—hence the conversion from utilDate.getTime().
2. Groovy's simplified Sql class (cleaner alternative)
Groovy provides the groovy.sql.Sql class which wraps JDBC to reduce boilerplate code, while still letting you specify data types when needed:
@Grab('org.codehaus.groovy:groovy-sql:3.0.17') // Grab the Groovy SQL dependency if needed import groovy.sql.Sql def sql = Sql.newInstance("jdbc:your_db_url", "username", "password", "com.your.db.Driver") def utilDate = new Date() // Explicitly pass java.sql.Date as the parameter sql.execute("INSERT INTO your_table (date_column) VALUES (?)", [new java.sql.Date(utilDate.getTime())]) // Or use Groovy's extension method for a shorter conversion sql.execute("INSERT INTO your_table (date_column) VALUES (?)", [utilDate.toSqlDate()]) sql.close()
Under the hood, groovy.sql.Sql still uses Java's PreparedStatement, so you get all the type safety and parameterized query benefits—with less code to write.
In short: All the JDBC functionality you know from Java works in Groovy, and Groovy adds convenient shortcuts to make your code more concise.
内容的提问来源于stack exchange,提问作者Hary

