Reputation: 35
I have an error while I'm trying to retrieve data from my sql database into a j combo box:
“You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax error”
public class NewJFrame extends javax.swing.JFrame {
Connection con=null;
PreparedStatement pst=null;
ResultSet rs=null;
/** Creates new form NewJFrame */
public NewJFrame() {
initComponents();
fillcombo();
}
private void fillcombo(){
try{
con=Connect.ConnectDB();
String sql="select * from leave";
pst=con.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next())
{
String nm=rs.getString("combo");
jComboBox1.addItem(nm);
}
}
catch(Exception e)
{ JOptionPane.showMessageDialog(null, e);
}
}
Upvotes: 1
Views: 166
Reputation: 201437
Please don't make fields from a Connection
or Statement
. LEAVE
is a mysql reserved word (so a table named leave must be escaped). Also, please don't select splat if you just want one column. Finally, you should close
your database resources (assuming you're using Java 7 or newer, you might use a try-with-resources
otherwise you'd need a finally
block) something like
String sql = "SELECT combo FROM `leave`";
try (Connection con = Connect.ConnectDB();
PreparedStatement pst = con.prepareStatement(sql);
ResultSet rs = pst.executeQuery()) {
if (rs.next()) {
String nm = rs.getString("combo");
jComboBox1.addItem(nm);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
Upvotes: 2