Inserting numeric data type using SQL statement in Java

John Vasiliou picture John Vasiliou · Feb 7, 2013 · Viewed 7.8k times · Source

I am writing a method which allows users to store their data within my database.

The problem I have is storing a numeric datatype in my database, for a user's ID.

Firstly, how can I tell if the ID number is auto-incrementing? These are it's properties:

Type: Numeric
Column size: 4
Decimal digits: 0
Part of primary key: true
Part of an index: true
Position: 1

I'm sure I read somewhere that, setting it as part of an index (true) allows for auto-incrementation. Can anyone confirm?

More importantly, when inserting data into my table I receive an error stating:

Columns of type 'NUMERIC' cannot hold values of type 'CHAR'. 

This is a snippet of my insert code (I can reveal more if need be):

Statement pStatement = conn.createStatement();
String selectSQL = ("INSERT INTO APP.PERSON VALUES ('" + '3' + "','" + user + "','" + pass + "','" + fName + "','" + sName + "','" + sQuestion + "','" + sAnswer + "') ");
pStatement.executeUpdate(selectSQL);

As you can see I am setting ID (the first value), to 3 manually. I believe this is throwing up the error and would like to know how to insert a numeric value, using the INSERT command.

I am coding in Java, using Netbeans 7.3 Beta 2, on Mac OS X Mountain Lion. I am using a Derby database.

Answer

shadrachJabonir picture shadrachJabonir · Feb 7, 2013

Hey bro I suggest u to use prepareStatement

String template = "INSERT INTO APP.PERSON VALUES (YOUR,TABLE,COLLUMN,NAME) values (?,?,?,?)";
           PreparedStatement stmt = yourConnection.prepareStatement(template);

So if your want to set your ID as an integer, let java do it with

       stmt.setInt(1, ID);
       stmt.setString(2, user);
       stmt.setString(3, fName);
       stmt.executeUpdate();

I dont know how is your table structure but this is an example if you want to use int use stmt.setInt(1, 3);

1--> position that u set up in string template

3--> maybe u want to hard coded the ID

here is my example pattern to use prepareStatement

String name = "shadrach"
Double price = "100.00"
int qty = 3;
    String template = "INSERT INTO PRODUCT (NAME,PRICE,QTY) values (?,?,?)";
                PreparedStatement stmt = connection.prepareStatement(template);
                stmt.setString(1, name);
                stmt.setDouble(2, price);
                stmt.setInt(3, qty);
                stmt.executeUpdate();