紧急有助:JDBC 连上数据库后函数调用的问题
我用JDBC 连接MySql,配置问题已经解决
以下是我的源代码
import java.sql.*;
public class Test
{
PreparedStatement statement;
String sql = " select CH from testdn where PA = \"A\"";
public static void main(String args[])
{
Test SQLExample = new Test();
}
public Test()
{
try{
Class.forName("org.gjt.mm.mysql.Driver");
String sourceURL =
new String("jdbc:mysql://localhost/testdn");
Connection databaseConnection =
DriverManager.getConnection(sourceURL,"root","1");
Statement statement = databaseConnection.createStatement();
//ResultSet r = statement.executeQuery(sql);
print();
}
catch(SQLException sqle){
System.err.println(sqle);
}
catch(ClassNotFoundException cnfe){
System.err.println(cnfe);
}
}
void print()
{
try{
ResultSet r = statement.executeQuery(sql);
while (r.next())
{
System.out.println("\n" + r.getString("CH"));
}
r.close();
}
catch(SQLException sqle)
{
System.err.println("\n SQLException ……\n");
System.err.println("SQLState:" + sqle.getSQLState());}
}
}
编译没问题,但在运行时出现问题
Exception in thread "main" java.lang.NullPointerException
at Test.print(Test.java:34)
at Test.<init>(Test.java:21)
at Test.main(Test.java:9)
为什么呢?如果在print 函数中加上参数ResultSet的话,运行就会顺利。为什么函数参数为空时就无法运行呢?
希望高手帮忙,多谢了!!