parameter query
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jdbc.test.JdbcMySqlUtil;
public class InputOutputParameter {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
// String sql = "insert into user (name,address) values (?,?)";
// System.out.println(update(sql,new String[]{"testName","testAddress"}));
String sql2 = "select * from user" ;
List<Map<String,Object>> list = query(sql2);
for (Map<String,Object> map:list)
{
for (String s:map.keySet())
System.out.print(s +" ");
for (Object obj:map.values())
System.out.print(obj+" ");
System.out.println();
}
}
private static int update(String sql,Object []args ) throws SQLException, ClassNotFoundException{
PreparedStatement ps = JdbcMySqlUtil.getInstance().getPrepareStatement(sql);
for (int i= 0 ; i < args.length ; i ++)
ps.setObject(i+1, args[i]);
int ret = ps.executeUpdate();
JdbcMySqlUtil.free(null, ps, ps.getConnection());
return ret ;
}
private static List<Map<String,Object>> query(String querySql) throws SQLException, ClassNotFoundException{
Statement st = JdbcMySqlUtil.getInstance().getStatement() ;
ResultSet rs = st.executeQuery(querySql);
ResultSetMetaData rsm = rs.getMetaData();
int colCount = rsm.getColumnCount();
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
while(rs.next())
{
Map<String,Object> map = new HashMap<String,Object>();
for (int i= 0 ; i < colCount ; i ++)
{
map.put(rsm.getColumnLabel(i+1), rs.getObject(i+1));
}
list.add(map);
}
JdbcMySqlUtil.free(rs, st, st.getConnection());
return list ;
}
}