473,401 Members | 2,146 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,401 software developers and data experts.

Java problem inserting a record into Access DB

94
Alright folks I am in need of a lil guidance/assistance here. I have a program which reads in a txt file. This txt file contains lines of the form

January 3, 2007, 85.8

Now each line of the txt file is to be read into my java program and then inserted (from the program into an Access Database). I am not exactly sure of where the problem lies. I know it has something to do with how I am parsing the file, or how I am passing my arguments to my insertRecord().

Ok enough chatter, here is the code I need help with.

This is the function reading the file obviously.

Expand|Select|Wrap|Line Numbers
  1. public static void readFile(String fileName)
  2. {
  3.     JDBC dbInstance = new JDBC();
  4.     String line;
  5.     try
  6.     {
  7.         BufferedReader in = new BufferedReader(new FileReader(fileName));
  8.         while((line = in.readLine())!= null)
  9.         {
  10.             StringTokenizer tokens = new StringTokenizer(line, ",");
  11.  
  12.                 String month = tokens.nextToken();
  13.                 String day = tokens.nextToken();
  14.                 String year = tokens.nextToken();
  15.                 String close = tokens.nextToken();
  16.                 double aDouble = Double.parseDouble(close);
  17.                 String date = month+" "+day;
  18.                 System.out.println(date+","+year+","+aDouble);
  19.  
  20.             dbInstance.insertRecord(date,year,aDouble);
  21.                 if(line == null)
  22.                 break;
  23.         //    System.out.println(line);
  24.             }
  25.         in.close();
  26.     }catch(Exception e)
  27.     {
  28.         System.out.println("error loading file or something. " + e.getMessage());
  29.     }
  30. }
  31.  

Here is the function inserting the records
Expand|Select|Wrap|Line Numbers
  1.        public void insertRecord(String Date, String Year, double Close )
  2.        {
  3.            String dateAndYear = Date+","+Year;
  4.            String data = "("+"'"+dateAndYear+"'"+","+Close+");";
  5.            String sqlRecord = "insert into Apple values " + data;
  6.            System.out.println ("record = " + sqlRecord);
  7.            try
  8.            {
  9.               db_statement.executeUpdate (sqlRecord);
  10.               System.out.println ("-= record inserted =-");
  11.               commitChanges();
  12.            } catch (Exception excep) {
  13.               System.out.println ("Unable to insert record: n" + excep);
  14.               System.exit(0);
  15.            }
  16.         }
  17.  
Lastly here is my createTable function, just in case anyone was interested:)

Expand|Select|Wrap|Line Numbers
  1.   public void createTable(String stockName)
  2.        {
  3.            String custTable = "CREATE TABLE "+ stockName +
  4.            "([Date] TEXT(50) NOT NULL, Close NUMBER NOT NULL)";
  5.            try 
  6.            {
  7.               db_statement.executeUpdate(custTable);
  8.               System.out.println ("-= table created =-");
  9.            } catch (Exception excep) {
  10.               System.out.println ("Unable to create table: n" + excep);
  11.               System.exit(0);
  12.            }
  13.         }
  14.  
I have been able to insert records if i hardcode them into my program directly (obviously I don't want to do this for thousands of records). I suppose my output may also be helpful for the brave soul who undertakes the role of my hero. It should also be noted that I am not a very experienced programmer so please "dumb" down any help you may have for the sake of my sanity:)


Output:
-= database driver loaded =-
-= connected to database to DB =- stocks
-= statement created =-
-= table created =-
January 3,2007,83.8
record = insert into Apple values ('January 3,2007',83.8);
Unable to insert record: njava.lang.NullPointerException
Sep 27 '07 #1
20 2975
dav3
94
ok I am pretty sure everything is ok in my code, as far as I can tell anyway. Its this nullPointerExceptin that is causing me to lose hair at a rapid rate!
Sep 27 '07 #2
r035198x
13,262 8TB
ok I am pretty sure everything is ok in my code, as far as I can tell anyway. Its this nullPointerExceptin that is causing me to lose hair at a rapid rate!
1.) Don't use StringTokenizer, use the String.split method instead.
2.) In your catch block, don't print the Exception's toString, call execption.printStackTrace() instead. That way you get full information about the exception.
3.) What does your commitChanges() method do?
Sep 27 '07 #3
dav3
94
1.) Don't use StringTokenizer, use the String.split method instead.
2.) In your catch block, don't print the Exception's toString, call execption.printStackTrace() instead. That way you get full information about the exception.
3.) What does your commitChanges() method do?
ty for your reply, I will try your recommendations tonight. My commitchanges() method just commits the changes to the database. Without it the records won't save to the database.
Sep 27 '07 #4
r035198x
13,262 8TB
ty for your reply, I will try your recommendations tonight. My commitchanges() method just commits the changes to the database. Without it the records won't save to the database.
By default connections are set to autoCommit true so your autoCommit method is probably redundant. There are only two suspects for that nullpointer and one of them is that autoCommit method of yours.
Sep 27 '07 #5
dav3
94
By default connections are set to autoCommit true so your autoCommit method is probably redundant. There are only two suspects for that nullpointer and one of them is that autoCommit method of yours.
I removed the commitchanges function and am still getting this pesky error about nullpointerexceptions. I tried leaving my code as is just commenting out commitchanges.
Sep 27 '07 #6
r035198x
13,262 8TB
I removed the commitchanges function and am still getting this pesky error about nullpointerexceptions. I tried leaving my code as is just commenting out commitchanges.

Did you use exception.printStackTrace() to see more about the exception?
Sep 27 '07 #7
dav3
94
it will not allow me to use Exception.printStackTrace(); perhaps im calling it incorrectly?

Expand|Select|Wrap|Line Numbers
  1. catch(Exception e)
  2.     {
  3.         System.out.println("error loading file or something. " + e.printStackTrace());
  4.     }
  5.  


EDIT: ah was adding it to the wrong catch:)
Sep 27 '07 #8
r035198x
13,262 8TB
it will not allow me to use Exception.printStackTrace(); perhaps im calling it incorrectly?

Expand|Select|Wrap|Line Numbers
  1. catch(Exception e)
  2.     {
  3.         System.out.println("error loading file or something. " + e.printStackTrace());
  4.     }
  5.  


EDIT: ah was adding it to the wrong catch:)
Have you found out the reason for the nullpointer then?
Sep 27 '07 #9
dav3
94
well it gave me 3 things to look at, and i cannot find a problem with any of the 3 statements.

Unable to insert record: njava.lang.NullPointerException
java.lang.NullPointerException
at JDBC.insertRecord(JDBC.java:69)
at gui_and_Main.readFile(gui_and_Main.java:30)
at gui_and_Main.main(gui_and_Main.java:57)

the lines in question are:

Expand|Select|Wrap|Line Numbers
  1.  db_statement.executeUpdate (sqlRecord);
Expand|Select|Wrap|Line Numbers
  1. dbInstance.insertRecord(date,aDouble);
Expand|Select|Wrap|Line Numbers
  1.       readFile("apple.txt");

This is all I am given, and cannot "conncet" the dots so to speak.
Sep 27 '07 #10
r035198x
13,262 8TB
well it gave me 3 things to look at, and i cannot find a problem with any of the 3 statements.

Unable to insert record: njava.lang.NullPointerException
java.lang.NullPointerException
at JDBC.insertRecord(JDBC.java:69)
at gui_and_Main.readFile(gui_and_Main.java:30)
at gui_and_Main.main(gui_and_Main.java:57)

the lines in question are:

Expand|Select|Wrap|Line Numbers
  1.  db_statement.executeUpdate (sqlRecord);
Expand|Select|Wrap|Line Numbers
  1. dbInstance.insertRecord(date,aDouble);
Expand|Select|Wrap|Line Numbers
  1.       readFile("apple.txt");

This is all I am given, and cannot "conncet" the dots so to speak.
Now put a println before
Expand|Select|Wrap|Line Numbers
  1. db_statement.executeUpdate (sqlRecord);
to check which variable is null at that point.

Probably db_statement itself is null at that point.

P.S Welcome to println debugging. The poor man's debugger.
Sep 27 '07 #11
dav3
94
ok inserted a line to see if either value was null, and they are both there. Could the problem be the whitespace? and if so, how do you get rid of it? I looked into it last night but could not get anything to work.
Sep 27 '07 #12
r035198x
13,262 8TB
ok inserted a line to see if either value was null, and they are both there. Could the problem be the whitespace? and if so, how do you get rid of it? I looked into it last night but could not get anything to work.
So you mean none of the values there is null? Come on there is a null reference there that's being dereferenced.
Sep 27 '07 #13
dav3
94
-= database driver loaded =-
-= connected to database to DB =- stocks
-= statement created =-
record = INSERT INTO Apple VALUES ('03-Jan-07' , 83.8);
test line 03-Jan-0783.8
Unable to insert record: njava.lang.NullPointerException
java.lang.NullPointerException
at JDBC.insertRecord(JDBC.java:70)
at gui_and_Main.readFile(gui_and_Main.java:30)
at gui_and_Main.main(gui_and_Main.java:57)


theres the output. Here is my current insertRecord();
Expand|Select|Wrap|Line Numbers
  1.  public void insertRecord(String Date, String Close )
  2.        {
  3.          //  String dateAndYear = Date+","+Year;
  4.            String data = "("+"'"+Date+"'"+" , "+Close+");";
  5.            String sqlRecord = "INSERT INTO Apple VALUES " + data;
  6.            System.out.println ("record = " + sqlRecord);
  7.            try
  8.            {
  9.                System.out.println("test line " + Date + Close);
  10.               db_statement.executeUpdate (sqlRecord);
  11.               System.out.println ("-= record inserted =-");
  12.             commitChanges();
  13.            } catch (Exception excep) {
  14.               System.out.println ("Unable to insert record: n" + excep);
  15.               excep.printStackTrace();
  16.               System.exit(0);
  17.            }
  18.         }
  19.  
Sep 27 '07 #14
r035198x
13,262 8TB
And where did you print the db_statement variable itself to check if it's null or not?
Sep 27 '07 #15
dav3
94
Not sure I understand now...

is that not what lines 5 and 6 of my previous post are doing?
Sep 27 '07 #16
r035198x
13,262 8TB
Not sure I understand now...

is that not what lines 5 and 6 of my previous post are doing?
Add this line and see what happens
Expand|Select|Wrap|Line Numbers
  1. System.out.println(db_statement); //add this line
  2. db_statement.executeUpdate(sqlRecord);
Sep 27 '07 #17
dav3
94
ok it says its null, but the statement hasnt been created yet? (no?)


Why the hell is it null?!


*confused*
Sep 27 '07 #18
r035198x
13,262 8TB
ok it says its null, but the statement hasnt been created yet? (no?)


Why the hell is it null?!


*confused*
Where did you initialize the db_statement variable?
It often helps to dry run the code and check to make sure that your flow ensures that all variables are properly initialized when they are needed.
Sep 27 '07 #19
dav3
94
but why will insertRecord(); work perfectly if i pass it say

Expand|Select|Wrap|Line Numbers
  1. dbInstance.insertRecord("01-11-07","89.7");


Ok through trial and error i stumbled upon a solution. I just need to move my db.Instance.loadDriver(); etc.... functions up to the readfile();

I think I see the reason for this, thank you for your help ro35198x. This is only step 4 of a MASSIVE project so rest assured I will be back:)

Thanks again.
Sep 27 '07 #20
r035198x
13,262 8TB
but why will insertRecord(); work perfectly if i pass it say

Expand|Select|Wrap|Line Numbers
  1. dbInstance.insertRecord("01-11-07","89.7");


Ok through trial and error i stumbled upon a solution. I just need to move my db.Instance.loadDriver(); etc.... functions up to the readfile();

I think I see the reason for this, thank you for your help ro35198x. This is only step 4 of a MASSIVE project so rest assured I will be back:)

Thanks again.
It's r035198x.
Sep 28 '07 #21

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Nick | last post by:
Is there a way to reference the 'primary key' field of a record you are actually inserting at the moment. Im using an 'int auto increment' field as the primary key. I could reference it with a...
133
by: Gaurav | last post by:
http://www.sys-con.com/story/print.cfm?storyid=45250 Any comments? Thanks Gaurav
3
by: James Alba | last post by:
Hey all, I am accessing an ms access database using .NET and C#. Like so, /* Create the database connection. */ connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data...
0
by: hzgt9b | last post by:
Using VS2003, VB.NET, Here's some pseudo code that I'm trying to get to work... if <a specific record existsthen do nothing else <insert the specific record> Endif I've got the code...
3
by: Surya | last post by:
Dear All, I have problem on inserting a record to database..Although it looked easy.. i have caught up with following issue .. please go ahead and help me to find solution I Need to insert...
0
by: freeskier | last post by:
Hello, Sorry for the newb question; I've spent a good amount of time trying to figure this out. I am fairly new to the Postgre world. I am currently in the process of upsizing several MS Access...
3
tjc0ol
by: tjc0ol | last post by:
Hi guys, Im a newbie in .NET, I follow the book in SitePoint which is Building your own ASP.NET Website using C# but I'm having trouble in inserting new data to MS ACCESS. When I run it, I've got an...
2
by: hakkatil | last post by:
Hi to all, I have a page that inserts excel sheet to access database. I am using asp. What I want to do is to check the inserting record if it is in the database. Basicly checking the dublicate...
5
by: rando1000 | last post by:
Okay, here's my situation. I need to loop through a file, inserting records based on a number field (in order) and if the character in a certain field = "##", I need to insert a blank record. ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.