Good morning everyone. I am having trouble connecting my MySQL database to a JTable in Eclipse. I keep on getting an exception and receiving this message "Unable to find and load database driver". Here is a sample of database code for the program:
class QueryTableModel extends AbstractTableModel
{
Vector cache;
int ColCount;
String[] headers;
Connection db=null;
Statement statement;
String driverName="com.mysql.jdbc.Driver";
//String driverName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
//String driverName = "com.jnetdirect.jsql.JSQLDriver";
//String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
String SQLLoadDatabaseQuery = "SELECT * FROM HouseHoldApplianceDatabase";
String URL = "jdbc:mysql://localhost:3306/DatabaseName";
// String serverName = "127.0.0.1";
// String portNumber = "1433";
//String mydatabase = serverName + ":" + portNumber;
//String currentURL = "jdbc:JSQLConnect://" + mydatabase;
//String username = "username";
// String password = "password";
public QueryTableModel()
{
cache = new Vector();
closeDB();
initDB(URL);
loadDB();
}
public String getColumnName(int i)
{
return headers[i];
}
public int getColumnCount()
{
return ColCount;
}
public int getRowCount()
{
return cache.size();
}
public Object getValueAt(int row, int col)
{
return ((String[]) cache.elementAt(row))[col];
}
public void loadDB()
{
cache = new Vector();
try {
ResultSet rs = statement.executeQuery(SQLLoadDatabaseQuery);
ResultSetMetaData meta = rs.getMetaData();
ColCount = meta.getColumnCount();
headers = new String[ColCount];
for (int h = 1; h <= ColCount; h++) {
headers[h - 1] = meta.getColumnName(h);
}
while (rs.next()) {
String[] record = new String[ColCount];
for (int i = 0; i < ColCount; i++) {
record[i] = rs.getString(i + 1);
}
cache.addElement(record);
}
fireTableChanged(null);
} catch (Exception e) {
e.printStackTrace();
System.err.println("Database still can't be loaded");
}
}
public void closeDB() {
try {
if (statement != null) {
statement.close();
}
if (db != null) {
db.close();
}
} catch (Exception e) {
System.out.println("Could not close the current connection.");
e.printStackTrace();
}
}
public void initDB(String url) {
try {
Class.forName(driverName).newInstance();
// Connection con = DriverManager.getConnection(url);
db = DriverManager.getConnection(url,"******","******");
statement = db.createStatement();
System.err.println("The database in initialized");
} catch (Exception e) {
System.err.println("Unable to find and load driver");
System.exit(1);
}
}
}
I omitted the username and password in this sample code for security purposes. I have also included the MySQL driver .jar file into the WEB/Inf folder and I still cannot connect the database into the JTable. Could anyone give me any suggestions to resolve this issue? I am using Eclipse 3.3 Java EE platform.