简体   繁体   English

尝试连接到MySQL时出现NullPointerException

[英]NullPointerException when trying to connect to MySQL

Please help me to identify why I always got this error : 请帮助我确定为什么总是出现此错误:

 java.lang.NullPointerException
    at TaskDAO.TaskDAO.main(TaskDAO.java:34)

Note: DatebaseHelper is a class which is using JDBC to connect to MySQL. 注意: DatebaseHelper是使用JDBC连接到MySQL的类。

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import TaskManagement.*;

public class TaskDAO {

    DatabaseHelper help;

    public static void main(String[] args) throws InstantiationException,
            IllegalAccessException, ClassNotFoundException, SQLException {

        TaskDAO taskDAO = new TaskDAO();

        int taskID = 6;
        String subject = "lau cua";
        Status status = Status.Completeted;
        Priority priority = Priority.High;
        Float percentage = 4f;
        String tableName = "tasks";
        String startDate = "2012/11/11";
        String dueDate = "2012/11/12";

        String query = "INSERT INTO "
                + tableName
                + "(taskID,subject,status,priority,percentage,startDate,dueDate)"
                + " VALUES ('" + taskID + "'," + "'" + subject + "'," + "'"
                + status + "'," + "'" + priority + "'," + "'" + percentage
                + "'," + "'" + startDate + "'," + "'" + dueDate + "')";

        taskDAO.help.executeQuery(query);
    }

}

DatabaseHelper help is a member variable, hence initialized to null . DatabaseHelper help是一个成员变量,因此初始化为null In main , you create a TaskDAO , and immediately use its help member - which is null . main ,您创建一个TaskDAO ,并立即使用它help成员-这是null You must initialize help with some valid DatabaseHelper . 您必须使用一些有效的DatabaseHelper初始化help

help is null ,so NPE忘记初始化它。

DatabaseHelper help = new DatabaseHelper();

You are calling taskDAO.help.executeQuery(query); 您正在调用taskDAO.help.executeQuery(query);
But till there DatabaseHelper help; 但是直到那里有DatabaseHelper help; is null because the reference variable is by default is null in java. 为null,因为在Java中引用变量默认为null。 So fist define DatabaseHelper help 因此,首先定义DatabaseHelper help

DatabaseHelper help = new DatabaseHelper();//or whatever create DatabaseHelper 

and then call 然后打电话

taskDAO.help.executeQuery(query);

A simple code to read from MySQL database is given below 下面给出了一个从MySQL数据库读取的简单代码

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;




public class NewClass {

public static void main(String[] args) {


    Connection conn = null;

    String url = "jdbc:mysql://192.168.100.100:3306/";
    String dbName = "databaseName";
    Statement stmt = null;
    ResultSet result = null;
    String driver = "com.mysql.jdbc.Driver";
    String databaseUserName = "admin";
    String databasePassword = "root";
    try {
        Class.forName(driver).newInstance();
        conn = DriverManager.getConnection(url + dbName, databaseUserName, databasePassword);
        stmt = conn.createStatement();
        result = null;
        String password,username;
        result = stmt.executeQuery("select * from userTable where username ='user1' ");
        if(!result.isBeforeFirst()){
            System.out.println("resultset contin no rows");
        }
        while (result.next()) {

            username=result.getString("username");
            password = result.getString("password");
            System.out.println(username+"  "+password);

        }
        conn.close();
    } catch (Exception e) {      
        e.printStackTrace();
    }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM