myeclipse 使用Java访问mysql数据库,数据库中有多条记录,为何只能读出一条数据??

Java 源代码如下:
public List<Msg> getAllMsgList() { List<Msg> msgList = new ArrayList<Msg>(); DBConnection db = new DBConnection(); Connection conn = db.getConn(); String sql = "select * from msg"; try { Statement pstmt = conn.createStatement(); ResultSet rs = pstmt.executeQuery(sql); if (rs.next()) { int id = rs.getInt(1); String content = rs.getString(2); String author = rs.getString(3); String publishiTime = rs.getString(4); Msg msg = new Msg(id, content, author, publishiTime); msgList.add(msg); } rs.close(); pstmt.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } return msgList; }

main函数:

IMsgDAO dao = new MsgDAOMysqlImpl(); List<Msg> msgList = dao.getAllMsgList();
for (Msg item : msgList) { System.out.println("id=" + item.getId() + "\tautor=" + item.getAutor() + "\tcontent=" + item.getContent() + "\tpublishiTime=" + item.getPublishiTime()); }

数据库内容:

输出显示:
id=1 autor=22 content=你是谁啊 publishiTime=20130717001624

你用的是if,没有执行循环,应该用 while

public List<Msg> getAllMsgList() {

  List<Msg> msgList = new ArrayList<Msg>();

  DBConnection db = new DBConnection();

  Connection conn = db.getConn();

  String sql = "select * from msg";

  try {

   Statement pstmt = conn.createStatement();

   ResultSet rs = pstmt.executeQuery(sql);

   while (rs.next()) {

    int id = rs.getInt(1);

    String content = rs.getString(2);

    String author = rs.getString(3);

    String publishiTime = rs.getString(4);

    Msg msg = new Msg(id, content, author, publishiTime);

    msgList.add(msg);

   }

   rs.close();

   pstmt.close();

   conn.close();

  } catch (SQLException e) {

   e.printStackTrace();

  }

  return msgList;

追问

哎呀 谢谢了 真是存心 菜鸟的学习生涯

温馨提示:内容为网友见解,仅供参考
第1个回答  2013-07-17
if (rs.next()) {
    int id = rs.getInt(1);
    String content = rs.getString(2);
    String author = rs.getString(3);
    String publishiTime = rs.getString(4);
    Msg msg = new Msg(id, content, author, publishiTime);
    msgList.add(msg);
   } 
//把 if 改成 while 代码如下:
while (rs.next()) {
    int id = rs.getInt(1);
    String content = rs.getString(2);
    String author = rs.getString(3);
    String publishiTime = rs.getString(4);
    Msg msg = new Msg(id, content, author, publishiTime);
    msgList.add(msg);
   } 
   
//祝你好运

追问

非常感谢 可是满意答案只能采纳一个 真想都采纳了 真是不好意思哈

第2个回答  2013-07-17
要用循环语句
相似回答