Last active
July 28, 2016 07:39
-
-
Save tasdemirbahadir/5435a93eadd4b530da2266ed90c5ea39 to your computer and use it in GitHub Desktop.
Set Nullable Value to the PreparedStatement Easily
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use this method to set values for PreparedStatemtn when using JDBC library with Java and MySQL. Otherwise your code would not look like readable.