2009年6月14日

JSTL ResultSupport

The Jakarta Taglibs Project
ResultSupport

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Arrays;
import java.util.Map;

import javax.servlet.jsp.jstl.sql.Result;
import javax.servlet.jsp.jstl.sql.ResultSupport;

public class Main {

public static void main(String[] args) throws Exception {
Result result = null;
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
String jdbcUrl = "jdbc:derby:testdb;create=true";
Connection conn = DriverManager.getConnection(jdbcUrl);
try {
Statement st = conn.createStatement();
try {
st.addBatch("create table table1(name char(10), id int, PRIMARY KEY (id))");
st.addBatch("insert into table1 values ('hello', 1)");
st.addBatch("insert into table1 values ('world', 2)");
st.executeBatch();
} finally {
st.close();
}

String sql = "select name, id from table1";
PreparedStatement ps = conn.prepareStatement(sql);
try {
ResultSet rs = ps.executeQuery();
result = ResultSupport.toResult(rs);
rs.close();
} finally {
ps.close();
}

} finally {
conn.close();
}
String[] ColumnNames = result.getColumnNames();
System.out.println(Arrays.toString(ColumnNames));

Map[] rows = result.getRows();
for (Map row : rows) {
for (String name : ColumnNames) {
System.out.print(row.get(name) + ", ");
}
System.out.println();
}
}

}
/*
[NAME, ID]
hello , 1,
world , 2,
*/

沒有留言:

網誌存檔