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


public 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;
JPanel panel;
public d4() {
    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() {
    panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    showButton = new JButton("Show");
    showButton.addActionListener(this);
//        lbl = recordsLabel();
//        for (JLabel jlabel : lbl) {
//            panel.add(jlabel);               // Make no sense , Why?
//        }
    panel.add(showButton);
    return panel;
}
public static void main(String[] args) {
    new d4();
}
@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == showButton) {
//
    }
}
    public JLabel[] recordsLabel() {
    try {
        Statement st1 = con.createStatement();
        ResultSet result1 = st1.executeQuery("select * from mytable");
        ArrayList<String> lableList = new ArrayList<>();
        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 (SQLException sqle) {
        System.out.println("Can not excute sql statement");
        sqle.printStackTrace();
    }
    return lbl;
}
}

输出:

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后中断,并仅向方法的调用方返回第一条记录。

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并填充一些集合,并在循环结束后在方法末尾返回集合。此外,创建标签 ,您只创建了一个标签,并从 showRecords2() 方法的返回值设置其文本。

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

while (result1.next()) {
        System.out.println(result1.getString(1) + " " + result1.getString(2));
        // Create your label here, for the current text
}

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

你可以试试

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]);
}

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

试试这段代码:

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;
}

}

很好用:

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;
}}

最新更新