Kan nån förklara för mig varför det bara fungerar i det första av kodexemplen? Det andra genererar NullpointerException vid den fetmarkerade raden.. Något jag inte förstår, eftersom dom gör exakt samma sak..
import java.sql.*;
public class HelloMySQL {
Connection connection;
private void displaySQLErrors(SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}
public HelloMySQL() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("Driver loaded");
} catch (Exception e) {
System.err.println("Unable to find and load driver");
System.exit(1);
}
}
public void connectToDB() {
try {
Connection connection = null;
String url = "jdbc:mysql://localhost/cbbook";
String user = "cbuser";
String password = "cbpass";
connection = DriverManager.getConnection(url, user, password);
System.out.println("Connected");
Statement statement = connection.createStatement( );
statement.executeQuery("SHOW TABLES");
ResultSet rs = statement.getResultSet( );
while (rs.next( ))
System.out.println(rs.getString(1) + "<br />");
rs.close( );
statement.close( );
connection.close( );
System.out.println("Connection closed");
} catch(SQLException e) {
displaySQLErrors(e);
}
}
public static void main(String[] args) {
HelloMySQL hello = new HelloMySQL();
hello.connectToDB();
}
}
\----------------------------------------------------------------
import java.sql.*;
public class HelloMySQL {
Connection connection;
private void displaySQLErrors(SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("SQLState: " + e.getSQLState());
System.out.println("VendorError: " + e.getErrorCode());
}
public HelloMySQL() {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
System.out.println("Driver loaded");
} catch (Exception e) {
System.err.println("Unable to find and load driver");
System.exit(1);
}
}
public void connectToDB() {
try {
Connection connection = null;
String url = "jdbc:mysql://localhost/cbbook";
String user = "cbuser";
String password = "cbpass";
connection = DriverManager.getConnection(url, user, password);
System.out.println("Connected");
} catch(SQLException e) {
displaySQLErrors(e);
}
}
public void executeSQL() {
try {
[b]Statement statement = connection.createStatement();[/b]
statement.executeQuery("SHOW TABLES");
ResultSet rs = statement.getResultSet( );
while (rs.next()) {
System.out.println(rs.getString(1) + "<br />");
}
rs.close( );
statement.close( );
connection.close( );
} catch(SQLException e) {
displaySQLErrors(e);
}
}
public static void main(String[] args) {
HelloMySQL hello = new HelloMySQL();
hello.connectToDB();
hello.executeSQL();
}
}