| Author |
Exception in thread "main" Error!
|
John Hood
Greenhorn
Joined: Aug 06, 2006
Posts: 6
|
|
when I try to copy the following statement mysql.executeUpdate("INSERT INTO Esitan VALUES(1,0,'0','y')"); from the structer function to a normal function.the error occurs.The progamme works perfectly when the statement is just in the stucture function. Any one can help me??thanks! the cource code: package exe; import db.SqlLink; import java.sql.*; public class Esitan { private SqlLink mysql; public Esitan() { //mysql SqlLink mysql=new SqlLink(); mysql.executeUpdate("drop table if exists Esitan"); mysql.executeUpdate("create table Esitan (id int not null auto_increment,parent INT not null ,value VARCHAR(50) not null,divided VARCHAR(2) not null ,primary key (id)); "); } void makefirstnode() { mysql.executeUpdate("INSERT INTO Esitan VALUES(1,0,'0','y')"); } public static void main(String[] args) { Esitan myEsitan=new Esitan(); myEsitan.makefirstnode(); } }
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24081
|
|
Hi, Welcome to JavaRanch! Note that what you're calling a "structure function" is actually called a "constructor" in English. Until I looked at your code, I couldn't guess what you were saying. In any case, you've made a mistake that almost everyone makes at least once: you have two different variables named "mysql." One is a member variable, declared in the class body. That's the one that the statement in the makefirstlink() method uses. The other one is declared in the constructor. Anytime you write the name of a type followed by the name of a variable, that's creating a new variable by that name. In this case, the new one "hides" the old one, so that all mentions of "mysql" in the constructor refer to this local variable. Because only the local one is initialized to refer to a SqlLink object, the member remains null, and this is why you get a NullPointerException in makefirstlink(). The solution is very simple: in your constructor, change this SqlLink mysql=new SqlLink(); to this mysql=new SqlLink();
|
[Jess in Action][AskingGoodQuestions]
|
 |
John Hood
Greenhorn
Joined: Aug 06, 2006
Posts: 6
|
|
Thanks a lot!Ernest,That's the point. I am new here and i am glad people here are quite warm-hearted. As a reply,I will try to use right words next time. thanks again!
|
 |
 |
|
|
subject: Exception in thread "main" Error!
|
|
|