Hello,
I need to create a JDBC that connects to a mySQL database, retrieves the data from a table and displays it into a JTable.
I have done this successfully, but have ran into a problem. The initial values I entered into the database (for testing) are permament. If I change the database values, save, close mySQL and re-execute the code it still displays the first set of values.
I reloaded mySQL to make sure it wasn't a problem with the database, but sure enough it shows the newly entered values.
Could someone please take a look at my code and show me where I have gone wrong? It's wrecking my head!
Thanks
package JDBC;
import java.sql.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class JDBCNew extends JPanel {
public Connection con = null;
public Statement stmt = null;
public ResultSet rs = null;
public JDBCNew() {
try{
String url = "jdbc:mysql://localhost:3306/myrecords";
String login = "root";
String password = "jdbc";
con = DriverManager.getConnection(url, login, password);
stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM employees");
ResultSetMetaData md = result.getMetaData();
int columnCount = md.getColumnCount();
Vector columns = new Vector(columnCount);
for(int i=1; i<=columnCount; i++)
columns.add(md.getColumnName(i));
Vector data = new Vector();
Vector row;
while(result.next())
{
row = new Vector(columnCount);
for(int i=1; i<=columnCount; i++)
{
row.add(result.getString(i));
}
data.add(row);
}
JTable table = new JTable(data, columns);
table.setPreferredScrollableViewportSize(new Dimension(300, 400));
table.setFillsViewportHeight(true);
// table.validate();
this.add(table);
}catch(SQLException sqle){
System.err.println(sqle);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Employee Records");
JScrollPane scrollPane = new JScrollPane(new JDBCNew());
frame.getContentPane().add(scrollPane);
frame.setSize(400, 500);
frame.setVisible(true);
}
}