下面列出了java.sql.PreparedStatement#setByte ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Theory
public void testBindByte(byte byteValue) throws SQLException
{
Connection connection = getConnection();
Statement statement = connection.createStatement();
statement.execute("create or replace table test_bind_byte(c1 integer)");
PreparedStatement preparedStatement = connection.prepareStatement(
"insert into test_bind_byte values (?)");
preparedStatement.setByte(1, byteValue);
preparedStatement.executeUpdate();
preparedStatement = connection.prepareStatement(
"select * from test_bind_byte where c1 = ?");
preparedStatement.setInt(1, byteValue);
ResultSet resultSet = preparedStatement.executeQuery();
assertThat(resultSet.next(), is(true));
assertThat(resultSet.getByte("C1"), is(byteValue));
resultSet.close();
preparedStatement.close();
statement.execute("drop table if exists test_bind_byte");
connection.close();
}
@Override
public boolean insertBindPoint(Player player) {
Connection con = null;
try {
con = DatabaseFactory.getConnection();
PreparedStatement stmt = con.prepareStatement(INSERT_QUERY);
BindPointPosition bpp = player.getBindPoint();
stmt.setInt(1, player.getObjectId());
stmt.setInt(2, bpp.getMapId());
stmt.setFloat(3, bpp.getX());
stmt.setFloat(4, bpp.getY());
stmt.setFloat(5, bpp.getZ());
stmt.setByte(6, bpp.getHeading());
stmt.execute();
stmt.close();
}
catch (Exception e) {
log.error("Could not store BindPointPosition data for player " + player.getObjectId() + " from DB: " + e.getMessage(), e);
return false;
}
finally {
DatabaseFactory.close(con);
}
return true;
}
@Override
public PreparedStatement prepareStatement(Connection connection) throws SQLException {
PreparedStatement statement = connection.prepareStatement(query);
statement.setLong(1, time);
statement.setString(2, reporterPlayer.getUsername());
statement.setString(3, reported);
statement.setByte(4, reason);
statement.setString(5, chatlog.toString());
statement.setInt(6, reporterPlayer.getX());
statement.setInt(7, reporterPlayer.getY());
statement.setInt(8, reported_x);
statement.setInt(9, reported_y);
statement.setBoolean(10, suggestsOrMutes);
statement.setBoolean(11, triedApplyAction);
return statement;
}
public static void deleteTask(PhoenixConnection conn, PTable.TaskType taskType, Timestamp ts, String tenantId,
String schemaName, String tableName, boolean accessCheckEnabled) throws IOException {
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement("DELETE FROM " +
PhoenixDatabaseMetaData.SYSTEM_TASK_NAME +
" WHERE " + PhoenixDatabaseMetaData.TASK_TYPE + " = ? AND " +
PhoenixDatabaseMetaData.TASK_TS + " = ? AND " +
PhoenixDatabaseMetaData.TENANT_ID + (tenantId == null ? " IS NULL " : " = '" + tenantId + "'") + " AND " +
PhoenixDatabaseMetaData.TABLE_SCHEM + (schemaName == null ? " IS NULL " : " = '" + schemaName + "'") + " AND " +
PhoenixDatabaseMetaData.TABLE_NAME + " = ?");
stmt.setByte(1, taskType.getSerializedValue());
stmt.setTimestamp(2, ts);
stmt.setString(3, tableName);
} catch (SQLException e) {
throw new IOException(e);
}
mutateSystemTaskTable(conn, stmt, accessCheckEnabled);
}
private void updateSignedTable(Connection conn, double data) throws Exception {
PreparedStatement stmt = conn.prepareStatement(
"UPSERT INTO " + signedTableName + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
stmt.setString(1, KEY);
Double d = Double.valueOf(data);
stmt.setBigDecimal(2, BigDecimal.valueOf(data));
stmt.setDouble(3, d.doubleValue());
stmt.setFloat(4, d.floatValue());
stmt.setInt(5, d.intValue());
stmt.setLong(6, d.longValue());
stmt.setShort(7, d.shortValue());
stmt.setByte(8, d.byteValue());
stmt.executeUpdate();
conn.commit();
}
public void testBigDecimal() throws Throwable {
String crtab = "create table #testBigDecimal (a decimal(28,10) NULL)";
dropTable("#testBigDecimal");
Statement stmt = con.createStatement();
stmt.executeUpdate(crtab);
stmt.close();
PreparedStatement pstmt = con.prepareStatement("insert into #testBigDecimal values (?)");
pstmt.setObject(1, new BigDecimal("10.200"));
pstmt.execute();
// FIXME With Sybase this should probably throw a DataTruncation, not just a plain SQLException
pstmt.setObject(1, new BigDecimal(10.200));
pstmt.execute();
pstmt.setObject(1, null);
pstmt.execute();
pstmt.setObject(1, new Integer(20));
pstmt.execute();
pstmt.setObject(1, new Double(2.10));
pstmt.execute();
pstmt.setObject(1, new BigDecimal(-10.200));
pstmt.execute();
pstmt.setObject(1, new Long(200));
pstmt.execute();
pstmt.setByte(1, (byte) 1);
pstmt.execute();
pstmt.setInt(1, 200);
pstmt.execute();
pstmt.setLong(1, 200L);
pstmt.execute();
pstmt.setFloat(1, (float) 1.1);
pstmt.execute();
pstmt.setDouble(1, 1.1);
pstmt.execute();
pstmt.close();
}
private void updateUnsignedTable(Connection conn, double data) throws Exception {
PreparedStatement stmt = conn.prepareStatement(
"UPSERT INTO " + unsignedTableName + " VALUES (?, ?, ?, ?, ?, ?, ?)");
stmt.setString(1, KEY);
Double d = Double.valueOf(data);
stmt.setDouble(2, d.doubleValue());
stmt.setFloat(3, d.floatValue());
stmt.setInt(4, d.intValue());
stmt.setLong(5, d.longValue());
stmt.setShort(6, d.shortValue());
stmt.setByte(7, d.byteValue());
stmt.executeUpdate();
conn.commit();
}
private void updateSignedTable(Connection conn, double data) throws Exception {
PreparedStatement stmt = conn.prepareStatement(
"UPSERT INTO " + signedTableName + " VALUES (?, ?, ?, ?, ?, ?, ?)");
stmt.setString(1, KEY);
Double d = Double.valueOf(data);
stmt.setDouble(2, d.doubleValue());
stmt.setFloat(3, d.floatValue());
stmt.setInt(4, d.intValue());
stmt.setLong(5, d.longValue());
stmt.setShort(6, d.shortValue());
stmt.setByte(7, d.byteValue());
stmt.executeUpdate();
conn.commit();
}
private void updateTableSpec(Connection conn, double data, String tableName) throws Exception {
PreparedStatement stmt =
conn.prepareStatement("UPSERT INTO " + tableName + " VALUES (?, ?, ?, ?, ?, ?, ?)");
stmt.setString(1, KEY);
Double d = Double.valueOf(data);
stmt.setDouble(2, d.doubleValue());
stmt.setFloat(3, d.floatValue());
stmt.setInt(4, d.intValue());
stmt.setLong(5, d.longValue());
stmt.setShort(6, d.shortValue());
stmt.setByte(7, d.byteValue());
stmt.executeUpdate();
conn.commit();
}
/**
* {@inheritDoc}
*/
@Override
public boolean updateAccount(Account account) {
int result = 0;
PreparedStatement st = DB
.prepareStatement("UPDATE account_data SET `name` = ?, `password` = ?, access_level = ?, membership = ?, last_server = ?, last_ip = ?, last_mac = ?, ip_force = ?, return_account = ?, return_end = ? WHERE `id` = ?");
try {
st.setString(1, account.getName());
st.setString(2, account.getPasswordHash());
st.setByte(3, account.getAccessLevel());
st.setByte(4, account.getMembership());
st.setByte(5, account.getLastServer());
st.setString(6, account.getLastIp());
st.setString(7, account.getLastMac());
st.setString(8, account.getIpForce());
st.setByte(9, account.getReturn());
st.setTimestamp(10, account.getReturnEnd());
st.setInt(11, account.getId());
st.executeUpdate();
}
catch (SQLException e) {
log.error("Can't update account");
}
finally {
DB.close(st);
}
return result > 0;
}
public void set(PreparedStatement st, Object value, int index) throws SQLException {
st.setByte( index, ( (Byte) value ).byteValue() );
}
public int setSqlParameters(PreparedStatement pstmt, int startIndex, SqlQuery query) throws SQLException
{
pstmt.setByte(startIndex, parameter);
return 1;
}
public static void setField(PreparedStatement upload, int type, Object field, int index) throws SQLException {
if (field == null) {
upload.setNull(index + 1, type);
} else {
try {
// casting values as suggested by http://docs.oracle.com/javase/1.5.0/docs/guide/jdbc/getstart/mapping.html
switch (type) {
case java.sql.Types.NULL:
upload.setNull(index + 1, type);
break;
case java.sql.Types.BOOLEAN:
case java.sql.Types.BIT:
upload.setBoolean(index + 1, (boolean) field);
break;
case java.sql.Types.CHAR:
case java.sql.Types.NCHAR:
case java.sql.Types.VARCHAR:
case java.sql.Types.LONGVARCHAR:
case java.sql.Types.LONGNVARCHAR:
upload.setString(index + 1, (String) field);
break;
case java.sql.Types.TINYINT:
upload.setByte(index + 1, (byte) field);
break;
case java.sql.Types.SMALLINT:
upload.setShort(index + 1, (short) field);
break;
case java.sql.Types.INTEGER:
upload.setInt(index + 1, (int) field);
break;
case java.sql.Types.BIGINT:
upload.setLong(index + 1, (long) field);
break;
case java.sql.Types.REAL:
upload.setFloat(index + 1, (float) field);
break;
case java.sql.Types.FLOAT:
case java.sql.Types.DOUBLE:
upload.setDouble(index + 1, (double) field);
break;
case java.sql.Types.DECIMAL:
case java.sql.Types.NUMERIC:
upload.setBigDecimal(index + 1, (java.math.BigDecimal) field);
break;
case java.sql.Types.DATE:
upload.setDate(index + 1, (java.sql.Date) field);
break;
case java.sql.Types.TIME:
upload.setTime(index + 1, (java.sql.Time) field);
break;
case java.sql.Types.TIMESTAMP:
upload.setTimestamp(index + 1, (java.sql.Timestamp) field);
break;
case java.sql.Types.BINARY:
case java.sql.Types.VARBINARY:
case java.sql.Types.LONGVARBINARY:
upload.setBytes(index + 1, (byte[]) field);
break;
default:
upload.setObject(index + 1, field);
LOG.warn("Unmanaged sql type ({}) for column {}. Best effort approach to set its value: {}.",
type, index + 1, field);
// case java.sql.Types.SQLXML
// case java.sql.Types.ARRAY:
// case java.sql.Types.JAVA_OBJECT:
// case java.sql.Types.BLOB:
// case java.sql.Types.CLOB:
// case java.sql.Types.NCLOB:
// case java.sql.Types.DATALINK:
// case java.sql.Types.DISTINCT:
// case java.sql.Types.OTHER:
// case java.sql.Types.REF:
// case java.sql.Types.ROWID:
// case java.sql.Types.STRUC
}
} catch (ClassCastException e) {
// enrich the exception with detailed information.
String errorMessage = String.format(
"%s, field index: %s, field value: %s.", e.getMessage(), index, field);
ClassCastException enrichedException = new ClassCastException(errorMessage);
enrichedException.setStackTrace(e.getStackTrace());
throw enrichedException;
}
}
}
private void minion_4889( Connection conn, int value, boolean expectedBooleanResult )
throws Exception
{
goodStatement( conn, "delete from t_4889" );
PreparedStatement ps = chattyPrepare
(
conn,
"insert into t_4889( key_col, setter_col, boolean_col ) values ( ?, ?, ? )"
);
ps.setInt( 1, 1 );
ps.setString( 2, "setByte" );
ps.setByte( 3, (byte) value );
ps.execute();
ps.setInt( 1, 2 );
ps.setString( 2, "setShort" );
ps.setShort( 3, (short) value );
ps.execute();
ps.setInt( 1, 3 );
ps.setString( 2, "setInt" );
ps.setInt( 3, value );
ps.execute();
ps.setInt( 1, 4 );
ps.setString( 2, "setLong" );
ps.setLong( 3, (long) value );
ps.execute();
ps.setInt( 1, 5 );
ps.setString( 2, "setObject( Byte )" );
ps.setObject( 3, new Byte( (byte) value ) );
ps.execute();
ps.setInt( 1, 6 );
ps.setString( 2, "setObject( Short )" );
ps.setObject( 3, new Short( (short) value ) );
ps.execute();
ps.setInt( 1, 7 );
ps.setString( 2, "setObject( Integer )" );
ps.setObject( 3, new Integer( value ) );
ps.execute();
ps.setInt( 1, 8 );
ps.setString( 2, "setObject( Long )" );
ps.setObject( 3, new Long( (long) value ) );
ps.execute();
String stringValue = Boolean.toString( (value != 0) );
assertResults
(
conn,
"select * from t_4889 order by key_col",
new String[][]
{
{ "1", "setByte", stringValue },
{ "2", "setShort", stringValue },
{ "3", "setInt", stringValue },
{ "4", "setLong", stringValue },
{ "5", "setObject( Byte )", stringValue },
{ "6", "setObject( Short )", stringValue },
{ "7", "setObject( Integer )", stringValue },
{ "8", "setObject( Long )", stringValue },
},
false
);
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Byte parameter, JdbcType jdbcType)
throws SQLException {
ps.setByte(i, parameter);
}
/**
* Determines how to map the given value to the appropriate JDBC data jdbcType and sets the parameter on the
* provided PreparedStatement
*
* @param stmt the PreparedStatement to set the parameter on
* @param attrName the name of the attribute that the parameter is coming from - for logging purposes
* @param parameterIndex the index of the HiveQL parameter to set
* @param parameterValue the value of the HiveQL parameter to set
* @param jdbcType the JDBC Type of the HiveQL parameter to set
* @throws SQLException if the PreparedStatement throws a SQLException when calling the appropriate setter
*/
protected void setParameter(final PreparedStatement stmt, final String attrName, final int parameterIndex, final String parameterValue, final int jdbcType) throws SQLException {
if (parameterValue == null) {
stmt.setNull(parameterIndex, jdbcType);
} else {
try {
switch (jdbcType) {
case Types.BIT:
case Types.BOOLEAN:
stmt.setBoolean(parameterIndex, Boolean.parseBoolean(parameterValue));
break;
case Types.TINYINT:
stmt.setByte(parameterIndex, Byte.parseByte(parameterValue));
break;
case Types.SMALLINT:
stmt.setShort(parameterIndex, Short.parseShort(parameterValue));
break;
case Types.INTEGER:
stmt.setInt(parameterIndex, Integer.parseInt(parameterValue));
break;
case Types.BIGINT:
stmt.setLong(parameterIndex, Long.parseLong(parameterValue));
break;
case Types.REAL:
stmt.setFloat(parameterIndex, Float.parseFloat(parameterValue));
break;
case Types.FLOAT:
case Types.DOUBLE:
stmt.setDouble(parameterIndex, Double.parseDouble(parameterValue));
break;
case Types.DECIMAL:
case Types.NUMERIC:
stmt.setBigDecimal(parameterIndex, new BigDecimal(parameterValue));
break;
case Types.DATE:
stmt.setDate(parameterIndex, new Date(Long.parseLong(parameterValue)));
break;
case Types.TIME:
stmt.setTime(parameterIndex, new Time(Long.parseLong(parameterValue)));
break;
case Types.TIMESTAMP:
stmt.setTimestamp(parameterIndex, new Timestamp(Long.parseLong(parameterValue)));
break;
case Types.CHAR:
case Types.VARCHAR:
case Types.LONGNVARCHAR:
case Types.LONGVARCHAR:
stmt.setString(parameterIndex, parameterValue);
break;
default:
stmt.setObject(parameterIndex, parameterValue, jdbcType);
break;
}
} catch (SQLException e) {
// Log which attribute/parameter had an error, then rethrow to be handled at the top level
getLogger().error("Error setting parameter {} to value from {} ({})", new Object[]{parameterIndex, attrName, parameterValue}, e);
throw e;
}
}
}
/**
* @param preparedState
* @param param
* @throws SQLException
*/
private void setParam(PreparedStatement preparedState, int index, PrepareSqlRequest.StateParam param) throws SQLException {
boolean isNull = (null == param.getValue());
Class<?> clazz;
try {
clazz = Class.forName(param.getClassName());
} catch (ClassNotFoundException e) {
throw new RuntimeException(e.getMessage(), e);
}
Rep rep = Rep.of(clazz);
switch (rep) {
case PRIMITIVE_CHAR:
case CHARACTER:
case STRING:
preparedState.setString(index, isNull ? null : String.valueOf(param.getValue()));
break;
case PRIMITIVE_INT:
case INTEGER:
preparedState.setInt(index, isNull ? 0 : Integer.valueOf(param.getValue()));
break;
case PRIMITIVE_SHORT:
case SHORT:
preparedState.setShort(index, isNull ? 0 : Short.valueOf(param.getValue()));
break;
case PRIMITIVE_LONG:
case LONG:
preparedState.setLong(index, isNull ? 0 : Long.valueOf(param.getValue()));
break;
case PRIMITIVE_FLOAT:
case FLOAT:
preparedState.setFloat(index, isNull ? 0 : Float.valueOf(param.getValue()));
break;
case PRIMITIVE_DOUBLE:
case DOUBLE:
preparedState.setDouble(index, isNull ? 0 : Double.valueOf(param.getValue()));
break;
case PRIMITIVE_BOOLEAN:
case BOOLEAN:
preparedState.setBoolean(index, !isNull && Boolean.parseBoolean(param.getValue()));
break;
case PRIMITIVE_BYTE:
case BYTE:
preparedState.setByte(index, isNull ? 0 : Byte.valueOf(param.getValue()));
break;
case JAVA_UTIL_DATE:
case JAVA_SQL_DATE:
preparedState.setDate(index, isNull ? null : java.sql.Date.valueOf(param.getValue()));
break;
case JAVA_SQL_TIME:
preparedState.setTime(index, isNull ? null : Time.valueOf(param.getValue()));
break;
case JAVA_SQL_TIMESTAMP:
preparedState.setTimestamp(index, isNull ? null : Timestamp.valueOf(param.getValue()));
break;
default:
preparedState.setObject(index, isNull ? null : param.getValue());
}
}
@Override
public void setNonNullParameter(PreparedStatement ps, int i, Byte parameter, JdbcType jdbcType) throws SQLException {
ps.setByte(i, parameter);
}
@Override
public String generateResult() throws Exception {
StringBuilder data = new StringBuilder();
PreparedStatement stmt = getConnection().prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
String param = params[i];
if (param.startsWith("%")) {
switch (param.charAt(1)) {
case 'B':
stmt.setBoolean(i + 1, Boolean.parseBoolean(param.substring(2)));
break;
case 'b':
stmt.setByte(i + 1, Byte.parseByte(param.substring(2)));
break;
case 's':
stmt.setShort(i + 1, Short.parseShort(param.substring(2)));
break;
case 'i':
stmt.setInt(i + 1, Integer.parseInt(param.substring(2)));
break;
case 'l':
stmt.setLong(i + 1, Long.parseLong(param.substring(2)));
break;
case 'f':
stmt.setFloat(i + 1, Float.parseFloat(param.substring(2)));
break;
case 'd':
stmt.setDouble(i + 1, Double.parseDouble(param.substring(2)));
break;
case 'n':
stmt.setBigDecimal(i + 1, new java.math.BigDecimal(param.substring(2)));
break;
case 'D':
stmt.setDate(i + 1, java.sql.Date.valueOf(param.substring(2)));
break;
case 't':
stmt.setTime(i + 1, java.sql.Time.valueOf(param.substring(2)));
break;
case 'T':
stmt.setTimestamp(i + 1, java.sql.Timestamp.valueOf(param.substring(2)));
break;
default:
throw new IllegalArgumentException("Unknown type prefix " + param);
}
}
else
stmt.setString(i + 1, param);
}
}
ResultSet rs;
try {
rs = stmt.executeQuery();
if (executeTwice()) {
rs.close();
rs = stmt.executeQuery();
}
}
catch (Exception ex) {
if (error == null)
forgetConnection();
throw ex;
}
ResultSetMetaData md = rs.getMetaData();
for (int i = 1; i <= md.getColumnCount(); i++) {
if (i > 1) data.append('\t');
data.append(md.getColumnLabel(i));
}
data.append('\n');
while (rs.next()) {
for (int i = 1; i <= md.getColumnCount(); i++) {
if (i > 1) data.append('\t');
data.append(rs.getString(i));
}
data.append('\n');
}
stmt.close();
return data.toString();
}
/**
Set the value into a PreparedStatement.
@exception SQLException Error setting value in PreparedStatement
*/
public final void setInto(PreparedStatement ps, int position) throws SQLException {
if (isNull()) {
ps.setNull(position, java.sql.Types.TINYINT);
return;
}
ps.setByte(position, value);
}