在oschina.net上看到了DBUtils项目,看介绍挺简单的,就准备尝试一下。
api确实非常简单,用起来很方便。
// Create a ResultSetHandler implementation to convert the
// first row into an Object[].
ResultSetHandler<Object[]> h = new ResultSetHandler<Object[]>() {
public Object[] handle(ResultSet rs) throws SQLException {
if (!rs.next()) {
return null;
}
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
Object[] result = new Object[cols];
for (int i = 0; i < cols; i++) {
result[i] = rs.getObject(i + 1);
}
return result;
}
};
// Create a QueryRunner that will use connections from
// the given DataSource
QueryRunner run = new QueryRunner(dataSource);
// Execute the query and get the results back from the handler
Object[] result = run.query(
"SELECT * FROM Person WHERE name=?", h, "John Doe");
ResultSetHandler<Object[]> h = ... // Define a handler the same as above example
// No DataSource so we must handle Connections manually
QueryRunner run = new QueryRunner();
Connection conn = ... // open a connection
try{
Object[] result = run.query(
conn, "SELECT * FROM Person WHERE name=?", h, "John Doe");
// do something with the result
} finally {
// Use this helper method so we don't have to check for null
DbUtils.close(conn);
}
QueryRunner run = new QueryRunner( dataSource );
try
{
// Execute the SQL update statement and return the number of
// inserts that were made
int inserts = run.update( "INSERT INTO Person (name,height) VALUES (?,?)",
"John Doe", 1.82 );
// The line before uses varargs and autoboxing to simplify the code
// Now it's time to rise to the occation...
int updates = run.update( "UPDATE Person SET height=? WHERE name=?",
2.05, "John Doe" );
// So does the line above
}
catch(SQLException sqle) {
// Handle it
}
遇到的问题:
用的时候发现,在做insert操作的时候报:
Exception in thread "Main Thread" java.sql.SQLException: Feature not implemented Query: insert into test (name) values (?) Parameters: [test0]
at org.apache.commons.dbutils.QueryRunner.rethrow(QueryRunner.java:542)
at org.apache.commons.dbutils.QueryRunner.update(QueryRunner.java:599)
at org.apache.commons.dbutils.QueryRunner.update(QueryRunner.java:575)
at com.allyes.icontext.fetcher.Test.main(Test.java:71)
后来发现原来是驱动的版本不对,开始用的3.1,改成5.1的就ok了。
以后直接需要操作jdbc的就用DBUtils就方便多了!