/**
* 查询一个sql语句.结果返回一个list集合
* @param sql
* @return
* @throws SQLException
*/
public List query(String sql) throws SQLException {
List list = new ArrayList();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Map map = null;
try {
//得到数据库连接
conn = JdbcUtils.getConnection();
//创建查询语句
ps = conn.prepareStatement(sql);
//得到ResultSetMetaData对象,从而获得结果集的所有信息,包括每一列的label
ResultSetMetaData rmd = ps.getMetaData();
int count = rmd.getColumnCount();
String label[] = new String[count];
for (int i = 1; i <= count; i++) {
label[i - 1] = rmd.getColumnLabel(i);
}
//执行sql语句
rs = ps.executeQuery();
//遍历每一行数据
while (rs.next()) {
map = new HashMap();
//处理一行数据,把列名和数据作为key,value存到map集合中
for (int i = 0; i < count; i++)
map.put(label[i], rs.getObject(label[i]));
//每一行数据作为一个对象添加到list集合中,返回给调用者
list.add(map);
}
//list的size()代表结果返回多少行数据
return list;
} finally {
//关闭资源
JdbcUtils.close(conn, ps, rs);
}
}
封装数据库连接和关闭的工具类
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public final class JdbcUtils {
private static final String url =
"jdbc:mysql://localhost:3306/struct?user=root&password=root";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError(e);
}
}
// 获得数据库连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url);
}
// 关闭数据库连接
public static void close(Connection conn, Statement stmt, ResultSet rs)
throws SQLException {
try {
if (rs != null)
rs.close();
} finally {
try {
if (stmt != null)
stmt.close();
} finally {
if (conn != null)
conn.close();
}
}
}
}