Skip to content

Instantly share code, notes, and snippets.

@tasdemirbahadir
Last active July 28, 2016 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tasdemirbahadir/5435a93eadd4b530da2266ed90c5ea39 to your computer and use it in GitHub Desktop.
Save tasdemirbahadir/5435a93eadd4b530da2266ed90c5ea39 to your computer and use it in GitHub Desktop.
Set Nullable Value to the PreparedStatement Easily
/** Design pattern below provides setting nullable values to the prepared statement easily
* Set nullable value to PreparedStatement
* @param ps PreparedStatement object
* @param value Value to set
* @param type Type of the value at DBMS (ex: Types.VARCHAR)
* @param index Index of the value inside query string
* @return Given PreparedStatement object with the value set
* @throws SQLException
* @throws TypeConstraintException If the type of the given value not found
*/
public static PreparedStatement setNullableValue(PreparedStatement ps, Object value, int type, int index)
throws SQLException, TypeConstraintException {
if (value == null) {
ps.setNull(index, type);
} else {
if (value instanceof Integer) {
ps.setInt(index, (Integer)value);
} else if (value instanceof Boolean) {
ps.setBoolean(index, (Boolean)value);
} else if (value instanceof Double) {
ps.setDouble(index, (Double)value);
} else if (value instanceof Array) {
ps.setArray(index, (Array)value);
} else if (value instanceof BigDecimal) {
ps.setBigDecimal(index, (BigDecimal)value);
} else if (value instanceof BigDecimal) {
ps.setBigDecimal(index, (BigDecimal)value);
} else if (value instanceof Date) {
ps.setDate(index, (Date)value);
} else if (value instanceof java.util.Date) {
ps.setTimestamp(index, new Timestamp(((java.util.Date)value).getTime()));
} else if (value instanceof Float) {
ps.setFloat(index, (Float)value);
} else if (value instanceof Float) {
ps.setFloat(index, (Float)value);
} else if (value instanceof Long) {
ps.setLong(index, (Long)value);
} else if (value instanceof Short) {
ps.setShort(index, (Short)value);
} else if (value instanceof String) {
ps.setString(index, (String)value);
} else if (value instanceof Time) {
ps.setTime(index, (Time)value);
} else if (value instanceof Timestamp) {
ps.setTimestamp(index, (Timestamp)value);
} else if (value instanceof URL) {
ps.setURL(index, (URL)value);
} else {
throw new TypeConstraintException("Type of the given value could not be determined!");
}
}
return ps;
}
@tasdemirbahadir
Copy link
Author

Use this method to set values for PreparedStatemtn when using JDBC library with Java and MySQL. Otherwise your code would not look like readable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment