• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 291
  • Last Modified:

JDBC INSERT problems

I have tested the following:

      int update = statement1.executeUpdate(
            "INSERT INTO tablename " +
             "VALUES ('1', 10.25)");

and it works.

However if I want the values to be the result of method calls and not literally inserted, what syntax do i need?

      int update = statement1.executeUpdate(
            "INSERT INTO tablename " +
             "VALUES ('currentKey', 'z.getPrice()')");

this wont work even though currnetKey is an int and z.getName() returns a double.  I get a 'criteria mismatch problem'.  Do i need to wrap?  currentKey holds number in the db and z.getName() is for a column that holds decimal in the db.

confused.
0
RedRichard
Asked:
RedRichard
  • 4
1 Solution
 
CEHJCommented:
The simplest way is to use a PreparedStatement

String sql = "INSERT INTO tablename VALUES (?, ?)";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setInt(1, currentKey);
pstmt.setDouble(2, z.getPrice());
pstmt.executeUpdate();


0
 
CEHJCommented:
The sql would be better with the column names too:

String sql = "INSERT INTO tablename (col1, col2) VALUES (?, ?)";
0
 
RedRichardAuthor Commented:
Thanks CEHJ,

Prepared statements might help me cut down on the headaches my
style of sql was giving me!
0
 
CEHJCommented:
:-)
0
 
CEHJCommented:
Bear in mind that theoretically you may take a performance hit from a PS as they are designed to optimise queries in loops and that comes at an DBMS price. However, this should not be noticeable. If, for some reason, it is. Let us know.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now