/*
* Created on 2004-10-13
*/
/**
* @author liuwei
*/
import java.sql.*;
public class TestResultSet {
/**
*更新操作
*
* @param s
* @throws SQLException
*/
public static void updateRow(Statement s) throws SQLException {
ResultSet rs = s.executeQuery("Select * from test");
rs.next();
rs.updateString(1, "222");
rs.updateString(2, "LiuWei");
rs.updateObject(3, new Integer(3));
rs.updateRow();
}
/**
* 插入操作
*
* @param s
* @throws SQLException
*/
public static void insertRow(Statement s) throws SQLException {
//读取空的结果集,从中取得表的结构
ResultSet rs = s.executeQuery("Select * from test where 1<>1");
for (int i = 0; i < 1000; i++) {
rs.moveToInsertRow();
rs.updateObject(1, new String("333"));
rs.updateObject(2, new String("Leo"));
rs.updateObject(3, new Integer(3));
rs.insertRow();
}
}
public static void main(String[] args) {
Connection con = null;
try {
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
con = DriverManager
.getConnection(
"jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=pubs",
"sa", "");
//直接调用execute的操作
long begin = System.currentTimeMillis();
Statement s = con.createStatement();
for (int i = 0; i < 1000; i++)
s.execute("insert into test values('333','Leo', 3)");
long end = System.currentTimeMillis();
System.out.println(begin - end);
s.execute("delete from test");
//用ResultSet进行操作的性能测试
Statement ss = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
begin = System.currentTimeMillis();
insertRow(ss);
end = System.currentTimeMillis();
System.out.println(begin - end);
s.execute("delete from test");
//用批处理的性能
String sql = "insert into test values('333','Leo', 3)";
begin = System.currentTimeMillis();
Statement s3 = con.createStatement();
for (int i = 0; i < 1000; i++)
s3.addBatch(sql);
s3.executeBatch();
end = System.currentTimeMillis();
System.out.println(begin - end);
s.execute("delete from test");
/*
* while (rs.next()){ System.out.println(rs.getString(2)); }
*/
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
从结果中可以看出,这种方式的性能在不考虑读取表结构的操作时,还可接受(与直接insert性能查不多),但这种方式免去了用大量代码去拼Sql的工作。