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.
The default ResultSet type is TYPE_FORWARD_ONLY . Note: Not all databases and JDBC drivers support all ResultSet types. The method DatabaseMetaData.
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.
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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With