Java 单击按钮时JDBC在JLabel中显示记录

Java 单击按钮时JDBC在JLabel中显示记录,java,swing,jdbc,jlabel,Java,Swing,Jdbc,Jlabel,从循环内部删除return语句。一旦遇到return语句,循环就会中断,并仅向方法的调用方返回第一条记录 Connected to database successfully! 10 sajjad 11 hamed 12 mehdi 13 hasan 555 fcvc 5858 cccc 1200 world 10 sajjad 1200 world 1200 world 1200 world 555 yes 333 ttt 1200 world Number of rows is: 14 循

从循环内部删除return语句。一旦遇到return语句,循环就会中断,并仅向方法的调用方返回第一条记录

Connected to database successfully!
10 sajjad
11 hamed
12 mehdi
13 hasan
555 fcvc
5858 cccc
1200 world
10 sajjad
1200 world
1200 world
1200 world
555 yes
333 ttt
1200 world
Number of rows is: 14

循环遍历resultset并填充一些集合,循环结束后在方法末尾返回集合。同样创建标签,您只创建了一个标签,并根据showRecords2方法的返回值设置了标签的文本。

您应该在循环中创建标签,而不是返回值,因为它会在第一行之后中断迭代

while (result1.next()) {
        System.out.println(result1.getString(1) + " " + result1.getString(2));
// instead of returning from here , you can create labels and set the text
// and return a List of labels.
        return result1.getString(1) + " "+ result1.getString(2); 
}

不能多次读取每个ResultSet行。 但您可以存储结果值

你可以试试

while (result1.next()) {
        System.out.println(result1.getString(1) + " " + result1.getString(2));

        // Create your label here, for the current text
}

Set类中的toArray方法返回一个对象数组。 无法将对象数组强制转换为字符串数组

请尝试以下代码:

Statement st1 = con.createStatement();
ResultSet result1 = st1.executeQuery("select * from mytable");
Set<String> set = new HashSet<String>();
while (result1.next()) {
    String resultRow = result1.getString(1) + " " + result1.getString(2);
    System.out.println(resultRow);
    set.add(resultRow);
}
String[] resultRows = (String[])set.toArray();

int rows = result1.last() ? result1.getRow() : 0;
System.out.println("Number of rows is: " + rows);      // print 14 correctly!

for (int i = 0; i < rows; i++) {
    lbl = new JLabel[rows];
    lbl[i].setText(resultRows[i]);
}
您可以这样做:

public JLabel recordsLabel() {
    try {
        Statement st1 = con.createStatement();
        ResultSet result1 = st1.executeQuery("select * from mytable");
        Set<String> set = new HashSet<String>();
        while (result1.next()) {
            String resultRow = result1.getString(1) + " " + result1.getString(2);
            System.out.println(resultRow);
            set.add(resultRow);
        }
        Object[] arrayResultRow = set.toArray();

        System.out.println("Number of rows is: " + arrayResultRow.length);

        lbl = new JLabel[arrayResultRow.length];
        for (int i = 0; i < arrayResultRow.length; i++) {
             lbl[i]=new JLabel(arrayResultRow[i].toString());
        }

    } catch (SQLException sqle) {
        System.out.println("Can not excute sql statement");
        sqle.printStackTrace();
    }
    return null;
}

这是一个毫无例外的新版本

public JLabel recordsLabel() {
    try {
        Statement st1 = con.createStatement();
        ResultSet result1 = st1.executeQuery("select * from mytable");
        ArrayList<String> labelsList = new ArrayList<String>();
        while (result1.next()) {
            String resultRow = result1.getString(1) + " " + result1.getString(2);
            System.out.println(resultRow);
            labelsList.add(resultRow);
        }

        System.out.println("Number of rows is: " + labelsList.size());

        lbl = new JLabel[labelsList.size()];
        for (int i = 0; i < labelsList.size(); i++) {
            lbl[i]=new JLabel(labelsList.get(i));
        }

    } catch (SQLException sqle) {
        System.out.println("Can not excute sql statement");
        sqle.printStackTrace();
    }
    return null;
}
}

这很有效:

class d4 extends JFrame implements ActionListener {

Connection con;
String dbName = "mydb";
String bdUser = "root";
String dbPassword = "2323";
String dbUrl = "jdbc:mysql://localhost/mydb";
JButton showButton;
static JLabel[] lbl;

public d4() throws ClassNotFoundException {

    Class.forName("com.mysql.jdbc.Driver");
    try {
        con = DriverManager.getConnection(dbUrl, bdUser,dbPassword);
        System.out.println("Connected to database successfully!");

    } catch (SQLException ex) {
        System.out.println("Could not connect to database");
    }

    add(mypanel(), BorderLayout.PAGE_START);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 500);
    setLocation(300, 30);
    setVisible(true);
}

public JPanel mypanel() {
    JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    showButton = new JButton("Show");
    showButton.addActionListener(this);
    lbl = recordsLabel();
    for (JLabel jLabel : lbl) {
        panel.add(jLabel);

    }
    panel.add(showButton);

    return panel;
}

public static void main(String[] args) throws ClassNotFoundException {
    new d4();
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == showButton) {
        recordsLabel();     
        //     mypanel().add(recordsLabel());       // Error
    }
}

public JLabel[] recordsLabel() {
    try {
        Statement st1 = con.createStatement();
        ResultSet result1 = st1.executeQuery("select * from mytable");
        ArrayList<String> lableList = new ArrayList<String>();
        while (result1.next()) {
            String resultRow = result1.getString(1) + " " + result1.getString(2);
            System.out.println(resultRow);
            lableList.add(resultRow);
        }
        Object[] arrayResultRow = lableList.toArray();

        int rows = result1.last() ? result1.getRow() : 0;
        System.out.println("Number of rows is: " + rows);

        lbl = new JLabel[rows];
        for (int i = 0; i < rows; i++) {
            lbl[i] = new JLabel(arrayResultRow[i].toString());
        }

    } catch (Exception sqle) {
        System.out.println("Can not excute sql statement");
        sqle.printStackTrace();
        lbl=new JLabel[0];
    }
    return lbl;
}

而result1.next将迭代,只要有要获取的结果。无法知道结果集中有多少行。每一个系统。。。是一排。。。如果你想为每一行创建一个标签,你应该在系统完成后这样做。出…问题是什么?-1只要你不陈述你的问题,特别是在修正了一些明显错误的编辑之后,赏金就没有多大意义issues@ViktorSeifert我想在单击showbutton时看到jlabels,而不是在程序运行时看到。对不起。只需更改此部分:String dbUrl=jdbc:mysql://localhost/onbook
class d4 extends JFrame implements ActionListener {

Connection con;
String dbName = "mydb";
String bdUser = "root";
String dbPassword = "2323";
String dbUrl = "jdbc:mysql://localhost/mydb";
JButton showButton;
static JLabel[] lbl;

public d4() throws ClassNotFoundException {

    Class.forName("com.mysql.jdbc.Driver");
    try {
        con = DriverManager.getConnection(dbUrl, bdUser,dbPassword);
        System.out.println("Connected to database successfully!");

    } catch (SQLException ex) {
        System.out.println("Could not connect to database");
    }

    add(mypanel(), BorderLayout.PAGE_START);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 500);
    setLocation(300, 30);
    setVisible(true);
}

public JPanel mypanel() {
    JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    showButton = new JButton("Show");
    showButton.addActionListener(this);
    lbl = recordsLabel();
    for (JLabel jLabel : lbl) {
        panel.add(jLabel);

    }
    panel.add(showButton);

    return panel;
}

public static void main(String[] args) throws ClassNotFoundException {
    new d4();
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == showButton) {
        recordsLabel();     
        //     mypanel().add(recordsLabel());       // Error
    }
}

public JLabel[] recordsLabel() {
    try {
        Statement st1 = con.createStatement();
        ResultSet result1 = st1.executeQuery("select * from mytable");
        ArrayList<String> lableList = new ArrayList<String>();
        while (result1.next()) {
            String resultRow = result1.getString(1) + " " + result1.getString(2);
            System.out.println(resultRow);
            lableList.add(resultRow);
        }
        Object[] arrayResultRow = lableList.toArray();

        int rows = result1.last() ? result1.getRow() : 0;
        System.out.println("Number of rows is: " + rows);

        lbl = new JLabel[rows];
        for (int i = 0; i < rows; i++) {
            lbl[i] = new JLabel(arrayResultRow[i].toString());
        }

    } catch (Exception sqle) {
        System.out.println("Can not excute sql statement");
        sqle.printStackTrace();
        lbl=new JLabel[0];
    }
    return lbl;
}
class d4 extends JFrame implements ActionListener {

Connection con;
String dbName = "mydb";
String bdUser = "root";
String dbPassword = "2323";
String dbUrl = "jdbc:mysql://localhost/onbook";
JButton showButton;
static JLabel[] lbl;
JPanel myPanel;

public d4() throws ClassNotFoundException {

    Class.forName("com.mysql.jdbc.Driver");
    try {
        con = DriverManager.getConnection(dbUrl, bdUser,dbPassword);
        System.out.println("Connected to database successfully!");

    } catch (SQLException ex) {
        System.out.println("Could not connect to database");
    }


     showButton = new JButton("Show");
    showButton.addActionListener(this);
    add(showButton,BorderLayout.PAGE_END);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 500);
    setLocation(300, 30);
    setVisible(true);
}

public JPanel mypanel() {
    JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    lbl = recordsLabel();
    for (JLabel jLabel : lbl) {
        panel.add(jLabel);
    }
    return panel;
}

public static void main(String[] args) throws ClassNotFoundException {
    new d4();
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == showButton) {
        add(mypanel(), BorderLayout.PAGE_START); 
        setVisible(true);
        //     mypanel().add(recordsLabel());       // Error
    }

}

public JLabel[] recordsLabel() {
    try {
        Statement st1 = con.createStatement();
        ResultSet result1 = st1.executeQuery("select * from mytable");
        ArrayList<String> lableList = new ArrayList<String>();
        while (result1.next()) {
            String resultRow = result1.getString(1) + " " + result1.getString(2);
            System.out.println(resultRow);
            lableList.add(resultRow);
        }
        Object[] arrayResultRow = lableList.toArray();

        int rows = result1.last() ? result1.getRow() : 0;
        System.out.println("Number of rows is: " + rows);

        lbl = new JLabel[rows];
        for (int i = 0; i < rows; i++) {
            lbl[i] = new JLabel(arrayResultRow[i].toString());
        }

    } catch (Exception sqle) {
        System.out.println("Can not excute sql statement");
        sqle.printStackTrace();
        lbl=new JLabel[0];
    }
    return lbl;
}}