Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ResultSet, SetObject vs SetString/SetDate/etc

Tags:

I'd like to know whether anyone considers using PreparedStatement.setObject for all data types as bad practice when preparing a statement. A use case for this would be a DAO with a generic executeQuery() method which can be re-used for all queries without having to worry about its data types.

like image 793
S.D Avatar asked May 08 '11 12:05

S.D


People also ask

What is the default type of ResultSet in JDBC applications?

The default ResultSet type is TYPE_FORWARD_ONLY . Note: Not all databases and JDBC drivers support all ResultSet types. The method DatabaseMetaData.

What is the use of setString in Java?

setString. Sets the designated parameter to the given Java String value. The driver converts this to an SQL VARCHAR or LONGVARCHAR value (depending on the argument's size relative to the driver's limits on VARCHAR values) when it sends it to the database.

What is a ResultSet in Java?

A table of data representing a database result set, which is usually generated by executing a statement that queries the database. A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row.

What is RS next () in Java?

The next() method of the ResultSet interface moves the pointer of the current (ResultSet) object to the next row, from the current position. Statement stmt = con. createStatement(); ResultSet rs = stmt. executeQuery("Select * from MyPlayers"); rs. next();


1 Answers

You can do so.

E.g.

preparedStatement = connection.prepareStatement(SQL_INSERT); SqlUtil.setValues(preparedStatement, user.getName(), user.getPassword(), user.getAge()); 

with

public static void setValues(PreparedStatement preparedStatement, Object... values) throws SQLException {     for (int i = 0; i < values.length; i++) {         preparedStatement.setObject(i + 1, values[i]);     } } 

The JDBC driver will do the type checking. The only disadvantage is maybe the (minor) overhead, but this is negligible as compared to the better maintainable code you end up with. Also, most ORM frameworks like Hibernate/JPA also uses that deep under the covers.

like image 168
BalusC Avatar answered Sep 17 '22 00:09

BalusC