Re: I get a null pointer when running my applet
Heres two of my classes. The first one is the applet class. It
creates a DataConnection class. The DataConnection class queries an
access database.
//**************
//Applet class
//**************
package consultviewer;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Main2 extends javax.swing.JApplet{
JPanel jpan;
Panel panel;
int width = 794;
public void init(){
setSize(width, 500);
}
public Main2(){
DataConnection dc = new DataConnection();
DefaultListModel testing = dc.queryConnection("SELECT * FROM
newconsult;");
System.out.println(testing);
}
}
//**********
//DataConnection Class
//**********
package consultviewer;
import java.sql.*;
import javax.swing.DefaultListModel;
import javax.swing.*;
class DataConnection
{
String filename = "C:\\Documents and Settings\\Owner\\Consult.mdb";
public DefaultListModel queryConnection(String sql){
sql = sql.replace('"', '\'');
Connection connection = null; // manages connection
Statement statement = null; // query statement
DefaultListModel returnedResults = null;
// connect to database books and query database
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String database = "jdbc:odbc:Driver={Microsoft Access
Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}";
// add on to the end
// establish connection to database
connection = DriverManager.getConnection( database ,"","");
// create Statement for querying database
statement = connection.createStatement();
// query database
ResultSet resultSet = statement.executeQuery(sql);
// process query results
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
returnedResults = new DefaultListModel();
while ( resultSet.next()){
for ( int i = 1; i <= numberOfColumns; i++ ){
returnedResults.addElement(resultSet.getObject(i));
}
} // end while
} // end try
catch ( SQLException sqlException ) {
sqlException.printStackTrace();
System.exit( 1 );
} // end catch
catch ( ClassNotFoundException classNotFound ) {
classNotFound.printStackTrace();
System.exit( 1 );
} // end catch
finally // ensure statement and connection are closed properly
{
try {
statement.close();
connection.close();
} // end try
catch ( Exception exception ) {
System.out.println("it failed here");
exception.printStackTrace();
System.exit( 1 );
} // end catch
} // end finally
return returnedResults;
}
}