请帮我确定一直出现此错误的原因:
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);
}
}
答案 0 :(得分:3)
DatabaseHelper help
是一个成员变量,因此初始化为null
。在main
中,您创建了TaskDAO
,并立即使用其help
成员 - null
。您必须使用有效的help
初始化DatabaseHelper
。
答案 1 :(得分:2)
help is null ,so NPE
,忘了初始化它。
DatabaseHelper help = new DatabaseHelper();
答案 2 :(得分:0)
您正在呼叫taskDAO.help.executeQuery(query);
但是直到那里DatabaseHelper help;
为null,因为默认情况下引用变量在java中为null。
所以先定义DatabaseHelper help
DatabaseHelper help = new DatabaseHelper();//or whatever create DatabaseHelper
然后致电
taskDAO.help.executeQuery(query);
答案 3 :(得分: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();
}
}
}