How to pass values to database table?

Hi, people!

I need to parse values from textfile lines, and make sql for inserting that values into appropriate table. Each line has a form that looks like this one:

IdNum=xxxx;Name=抶x...x?Address=抶x...x?[LocalNum=xxxx;]Type=抶?

where IdNum, Name, Address, LocalNum and Type are name of columns, xxx are values and value in [ ] is optional columnname=value (columnname can have null values).

I managed to parse names of colums and values. Here is the code:

import java.util.*;

publicclass Strtok{

publicstaticvoid main(String [] args){

String str ="IdNum=xxxx;Name=抶x...x?Address=抶x...x?LocalNum=xxxx;Type=抶?";

StringTokenizer token =new StringTokenizer(str ,"= ;");

while (token.hasMoreElements())

System.out.println(token.nextElement());

}

}

and result is:

IdNum

xxxx

Name

抶x...x?br>Address

抶x...x?br>LocalNum

xxxx

Type

抶?br>

Now, how can I pass that values into insert query

INSERT INTO TableNAme (IDNum, Name, Address, LocalNum, Type)

VALUES (xxxx, 'xx...x', 'xx...x', xxxx,'x' );

?

[1582 byte] By [dalibora] at [2007-11-26 15:52:35]
# 1
Start by looking up JDBC.
Aknibbsa at 2007-7-8 22:12:54 > top of Java-index,Java Essentials,Java Programming...
# 2
I already read JDBC, but didn't find example that would help me. It is not complicated when I don't have optional values, but I have them....
dalibora at 2007-7-8 22:12:54 > top of Java-index,Java Essentials,Java Programming...
# 3

Why does the insert query need to know whether the values are optional or non-optional? That's handled by constraints in the database. Make that string without brackets regardless of whether or not it has optional fields in it, and it should work.

If it doesn't, please give a specific exception you are facing.

bheilersa at 2007-7-8 22:12:54 > top of Java-index,Java Essentials,Java Programming...
# 4

> I already read JDBC, but didn't find example that

> would help me. It is not complicated when I don't

> have optional values, but I have them....

Your problem is less about JDBC and more about what to do and how to detect the "missing" values.

What I would suggest is something like this.

For starters you should use a PreparedStatement in your JDBC code. That will make your code safer.

Then you might want to create a Properties instance or a simple class for each entry. This entry would encompass all the fields (names and values) that you might have.

For each line then fill in the object (your or Properties) with the values you have. Then set the parameters of your PreparedStatement instance with the values. What you will do is for values that are missing supply a default of some sort (like a zero length String) in your object or Properties.

cotton.ma at 2007-7-8 22:12:54 > top of Java-index,Java Essentials,Java Programming...