有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在NetBeans的JTextArea中显示Sql列

我正试图在NetBeans中制作一个聊天信使,在WAMP中使用Java前端和MySQL,但我想在jTextArea中显示注册用户,如图所示:

chat messenger frame

此外,我想补充一点,我的数据库已连接到应用程序

这是我用来显示的代码,虽然我没有收到任何错误,但也没有显示任何内容

try{
  Class.forName("com.mysql.jdbc.Driver"); 
  conn = DriverManager.getConnection("jdbc:mysql://localhost:3306","root",""); 
  String abc = "select user from ch.login"; 
  pst = conn.prepareStatement(abc); 
  rs= pst.executeQuery(abc); 
  chat cc=new chat(); 
  cc.jTextArea2.setText(abc);
}catch(ClassNotFoundException | SQLException e){
  JOptionPane.showMessageDialog(null,e);
}

共 (1) 个答案

  1. # 1 楼答案

    您必须首先使用rs.next()检查resultSet中是否有任何值,然后从resultSet中获取数据。因为您只选择了一列rs.getString(1),其中1是列的索引

    try{
      Class.forName("com.mysql.jdbc.Driver"); 
      conn = DriverManager.getConnection("jdbc:mysql://localhost:3306","root",""); 
      String abc = "select user from ch.login"; 
      pst = conn.prepareStatement(abc); 
      rs= pst.executeQuery(abc); 
      if(rs.next()){ // you can use while loop if you have more then one row in database
        chat cc=new chat(); 
        cc.jTextArea2.setText(rs.getString(1));
      }
    }catch(ClassNotFoundException | SQLException e){
      JOptionPane.showMessageDialog(null,e);
    }
    

    我再次建议您在编写自己的逻辑之前,先用MySQL为JDBC创建一两个示例程序