2012-07-02 66 views
0

請幫我找出爲什麼我總是得到這個錯誤時:NullPointerException異常試圖連接到MySQL

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

注: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); 
    } 

} 

回答

3
DatabaseHelper help

是一個成員變量,因此初始化爲null。在main中,您將創建一個TaskDAO,並立即使用其help成員 - 即null。您必須使用一些有效的DatabaseHelper初始化help

+0

給出感謝您爲您的快速回答,我在看它也許會要求你進一步的幫忙。再次感謝你。 – user1495278

2

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

DatabaseHelper help = new DatabaseHelper(); 
0

要調用taskDAO.help.executeQuery(query);
但直到有DatabaseHelper help;爲null,因爲引用變量在默認情況下是在Java空。 所以拳頭定義DatabaseHelper help

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

,然後調用

taskDAO.help.executeQuery(query); 
0

一個簡單的代碼從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(); 
    } 
} 
} 
相關問題