Tehnic
Tehnic

Reputation: 29

Can I put in a jLabel text from a database?

I need some help with a little project that I have to do for work. In this project I need to get a specific cell from the database, the query must look someting like this select * from app_1 where id_user_main=?

jLabel4 = new javax.swing.JLabel();
jLabel4.setText(null);
{
    String sql = "select * from info where id_user_main=?";  
    try {
        conn = MySQLConnect.ConnectDb();
        pst = conn.prepareStatement(sql);
        pst.setInt(1, id);
        rs = pst.executeQuery();

        if (rs.next()) { 
            jLabel4.setText(rs.getString("info"));
        }
    } catch(Exception e) {

    }   
}

Upvotes: 0

Views: 1797

Answers (1)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

Simply split your problem in two sub problems:

  • Retrieve the string from the database
  • Set the string to the label

As an example:

 public String getStringFromDb(String key) {
     ....
 }

 ....

 public void setLabel(String str, JLabel label) {
     label.setText(str);
 }

 ...

 public void setLabelFromDb(String key, JLabel label) {
     String str = getStringFromDb(key);
     setLabel(str, label);
 }

Upvotes: 2

Related Questions