我了解你想从你的用户数据库中收集的所有数据到一个列表:
public static List<User> getUsers() {
List<User> allUsers = new ArrayList<User>();
DataSource ds = MyDataSourceFactory.getMySQLDataSource();
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
con = open(con, ds);
String SQL = "SELECT id,name,address from YOUR DATA TABLE;
stmt = con.prepareStatement(SQL);
rs = stmt.executeQuery();
while (rs.next()) {
int i = rs.getInt("id");
String name = rs.getString("name");
String address = rs.getString("address");
User us = new Location(i,name,address);
locs.add(loc);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
close(stmt, con, rs);
}
return res;
}
这两种方法用于打开和关闭与数据库的连接:
public static Connection open(Connection con, DataSource ds)
throws SQLException {
try {
con = ds.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
if (con == null) {
throw new SQLException("cannot connect to database!");
}
return con;
}
public static void close(PreparedStatement preparedStatement,
Connection con, ResultSet rs) {
try {
if (rs != null)
rs.close();
if (preparedStatement != null)
preparedStatement.close();
if (con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
请告诉我们你到目前为止试过的东西。 –
你没有提供代码,所以这里是一个普通的答案:查询地址为“example2”的条目带有SQL-“select”语句,所以你只能得到匹配的条目,而不是所有条目。 – mumpitz