Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make PreparedStatement.setXXX() dynamic based on type of column values

Tags:

java

jdbc

I have to update table using values from a data file which contains all the rows. Now I am using JDBC batches. Data files contains 100s of columns and millions of rows.

For e.g. data file contains 3 columns two rows to make it simple

1,ABC,DEF
2.GHI,JKL

PreparedStatement pstmt = connection.prepareStatement(insert);
                //how to find type
                pstmt.setInt(1, 2);
                pstmt.setString(2, "GHI");
                pstmt.setString(3, "JKL");
                pstmt.addBatch();
                pstmt.executeBatch();

Now my question is at run time based on the data coming from data file how do I find that I need to call setInt or setString and more importantly how many times I need to call setXXX for that addBatch(). This seems like for each table I need to have dedicated preparedStatements. More importantly I need to find how many times I should call setObject at run based on the number of columns which is in data ile? Is there anyway I can make this generic?

I am new to JDBC please guide. Thanks in advance.

like image 353
Umesh K Avatar asked Mar 24 '23 06:03

Umesh K


1 Answers

You can use setObject(int index, Object obj). JDBC then determines the correct type.

like image 182
ssindelar Avatar answered Apr 06 '23 04:04

ssindelar