簡體   English   中英

單擊按鈕時,JDBC在JLabel中顯示記錄

[英]JDBC show records in JLabel when button clicked

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時將中斷,並僅向該方法的調用者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並填充一些Collection,並在循環結束后在方法末尾返回Collection。 同樣創建標簽,您僅創建了一個標簽,並從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方法返回一個對象數組。 您不能將Object數組轉換為String數組。

試試這個代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM