学习记录:使用JDBC连接数据库报NullPointerException。

最近在学习使用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.总结:敲代码的时候要细心,要明白每个步骤的作用。不要漏了代码。吸取经验教训。>.<

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值