I was trying to link MySQL with NetBeans for the first time. To do this, I wrote a suitable code and made a suitable design for JFrame form too. The JFrame file is not showing any error but it is not giving the desired output. It is not able to fetch the data from MySQL. Please find the attached code and additional information. Any kind of help will be really appreciated.
I made a JFrame form named 'Connect' having three jButtons and one jTable. The function of jButton1 is to retrieve data from 'DepTbl' table in MySQL and display it on jTable. Unfortunately, it is not giving the desired output. It is giving the output as written under catch{ statement, which is
'Error in connectivity.' in JOptionPane. Please read the code attached.
Coding I did:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model=(DefaultTableModel) jTable1.getModel();
try
{ Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection
("jdbc:mysql://localhost/PracticalExercises","root","tiger");
Statement stmt = con.createStatement();
String query = "SELECT * FROM DepTbl;";
ResultSet rs=stmt.executeQuery(query);
while(rs.next()){
String DeptNo=rs.getString("DeptNo");
String Dname=rs.getString("Dname");
String Location=rs.getString("Location");
model.addRow(new Object[] {DeptNo,Dname,Location});}
rs.close();
stmt.close();
con.close();}
catch (Exception e){
JOptionPane.showMessageDialog(null,"Error in connectivity.");
}
}
I expect it to retrieve the data from the table in MySQL and display it in jTable1. But, the result is in JOptionPane as "Error in connectivity." which is taken from statement under catch{.
e
wants to tell you. – Tomcatch (Exception e)
you catch the exception which itself contains the issue at hand. But you don't show that content ofe
, but rather chose to use a generic error message which doesn't help you that much. So displaye
instead to see what it wants to tell you. – Tom