用JDBC操作数据库,对比一下Java和Groovy。
环境:SQL Server 2000 (记得打补丁SP4,不然JDBC访问会报错)
JDBC Driver:msbase.jar,mssqlserver.jar,msutil.jar
Java版
package
jcat.bit.java;
import
java.sql.
*
;
public
class
JDBC {
public
static
void
main(String[] args)
throws
ClassNotFoundException, SQLException {
Class.forName(
"
com.microsoft.jdbc.sqlserver.SQLServerDriver
"
);
Connection conn
=
DriverManager.getConnection(
"
jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs
"
,
"
sa
"
,
"***
"
);
Statement stmt
=
conn.createStatement();
ResultSet rs
=
stmt.executeQuery(
"
select top 10 * from authors
"
);
while
(rs.next()) {
System.out.println(rs.getString(
2
)
+
"
"
+
rs.getString(
3
)); // 数id
}
rs.close();
stmt.close();
conn.close();
}
}
Groovy版
package jcat.bit.groovy
import groovy.sql.Sql
class JDBC {
static void main(args) {
Sql sql = Sql.newInstance(
"jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs",
"sa", "***",
"com.microsoft.jdbc.sqlserver.SQLServerDriver")
sql.eachRow("select top 10 * from authors") {row ->
println row.au_fname + " " + row.au_lname //直接用数据库的字段名就可以操作结果集了,不用去数id
}
}
}
总结
1. 建立查询,差别不大,都是JDBC那一套;Groovy不用处理异常
2. 处理查询结果,Groovy因为有闭包,
处理这些迭代问题很方便3. Groovy不用关闭
posted on 2008-11-07 15:02
Jcat 阅读(1661)
评论(3) 编辑 收藏 所属分类:
Java