最近在学习使用JDBC的过程中遇到了一个问题:mysql数据库驱动连接成功,数据库连接成功,数据库中对应查询有数据且SQL语句没写错,但报了空指针异常。
1.异常代码如下:
// 异常代码
package trytousemysql;
import java.sql.*;
public class JDBCtest01 {
static Connection connection=null;
static Statement sql;
static ResultSet resultSet;
static String url;
static String user;
static String password;
public Connection connection_1() throws SQLException {
url="jdbc:mysql://localhost:3306/teaching";
user="root";
password="123456";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("mysql数据库驱动加载成功");
connection=DriverManager.getConnection(url,user,password);
System.out.println("数据库连接成功");
System.out.println(connection);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return connection;
}
public void update() throws SQLException {
try {
resultSet=sql.executeQuery("select * from teaching.student");
while (resultSet.next()){
System.out.println("更新前:");
String studentno=resultSet.getString("studentno");
String sname=resultSet.getString("sname");
String sex=resultSet.getString("sex");
String birthdate=resultSet.getString("birthdate");
String entrance=resultSet.getString("entrance");
String phone=resultSet.getString("phone");
String Email=resultSet.getString("Email");
System.out.println(studentno+" "+sname+" "+sex+" "+birthdate+" "+entrance+" "+phone+" "+Email);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void main(String[] args) throws SQLException {
JDBCtest01 ctest01=new JDBCtest01();
ctest01.connection_1();
ctest01.update();
}
}
有如下异常:
2.原因是我在执行SQL语句前居然没有将connection接口的createstatement方法创建的对象传递给statement即:没有写下statement sql=connection.creastatement;
3.总结:敲代码的时候要细心,要明白每个步骤的作用。不要漏了代码。吸取经验教训。>.<