Java Code Examples for java.sql.PreparedStatement.setNull()

The following are Jave code examples for showing how to use setNull() of the java.sql.PreparedStatement class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: ChronoBike   File: RecordColTypeManagerTimestamp.java   Source Code and License Vote up 7 votes
public boolean transfer(int nColumnNumber1Based, ResultSet resultSetSource, PreparedStatement insertStatementInsert)
{
	try
	{			
		Timestamp value = resultSetSource.getTimestamp(m_nColSourceIndex);
		if (!resultSetSource.wasNull())
			insertStatementInsert.setTimestamp(m_nColSourceIndex, value);
		else
			insertStatementInsert.setNull(m_nColSourceIndex, Types.TIMESTAMP);
		return true;
	}
	catch (SQLException e)
	{
		e.printStackTrace();
	}
	return false;		
}
 
Example 2
Project: jaffa-framework   File: TypeDefs.java   Source Code and License Vote up 7 votes
/** Sets a parameter in the PreparedStatement.
 * @param engineType The engine type as defined in init.xml
 * @param pstmt The PreparedStatement.
 * @param parameterIndex The index of the parameter that is to be set.
 * @param value The object to be assigned to the parameter.
 * @throws SQLException if a database access error occurs.
 */
public void setAppObject(PreparedStatement pstmt, int parameterIndex, Object value, String engineType)
throws SQLException {
    if (value != null) {
        if (!(value instanceof String))
            value = DataTypeMapper.instance().map(value, String.class);
        if ("oracle".equalsIgnoreCase(engineType) && !supportsStdLob(pstmt)) {
            Clob clob = createClob(pstmt.getConnection(), (String) value);
            pstmt.setClob(parameterIndex, clob);
        } else {
            String str = (String) value;
            Reader reader = new BufferedReader(new StringReader(str));
            pstmt.setCharacterStream(parameterIndex, reader, str.length());
        }
    } else
        pstmt.setNull(parameterIndex, getSqlType(Defaults.CLOB, engineType));
}
 
Example 3
Project: lams   File: ByteArrayBlobType.java   Source Code and License Vote up 6 votes
protected void set(PreparedStatement st, Object value, int index, SessionImplementor session) throws SQLException {
	if ( value == null ) {
		st.setNull( index, sqlTypes( null )[0] );
	}
	else {
		byte[] toSet = unWrap( value );
		final boolean useInputStream = session.getFactory().getDialect().useInputStreamToInsertBlob();

		if ( useInputStream ) {
			st.setBinaryStream( index, new ByteArrayInputStream( toSet ), toSet.length );
		}
		else {
			st.setBlob( index, Hibernate.getLobCreator( session ).createBlob( toSet ) );
		}
	}
}
 
Example 4
Project: ChronoBike   File: RecordColTypeManagerVarchar.java   Source Code and License Vote up 6 votes
public boolean transfer(int nColumnNumber1Based, ResultSet resultSetSource, PreparedStatement insertStatementInsert)
{
	try
	{			
		String csValue = resultSetSource.getString(m_nColSourceIndex);
		if (!resultSetSource.wasNull())
			insertStatementInsert.setString(m_nColSourceIndex, csValue);
		else
			insertStatementInsert.setNull(m_nColSourceIndex, Types.VARCHAR);
		return true;
	}
	catch (SQLException e)
	{
		e.printStackTrace();
	}
	return false;		
}
 
Example 5
Project: ChronoBike   File: RecordColTypeManagerDecimalLong.java   Source Code and License Vote up 6 votes
public boolean transfer(int nColumnNumber1Based, ResultSet resultSetSource, PreparedStatement insertStatementInsert)
{
	try
	{
		long lValue = resultSetSource.getInt(m_nColSourceIndex);
		if (!resultSetSource.wasNull())
			insertStatementInsert.setLong(m_nColSourceIndex, lValue);
		else
			insertStatementInsert.setNull(m_nColSourceIndex, Types.INTEGER);
		return true;
	}
	catch (SQLException e)
	{
		e.printStackTrace();
	}
	return false;		
}
 
Example 6
Project: ChronoBike   File: RecordColTypeManagerDecimal.java   Source Code and License Vote up 6 votes
public boolean transfer(int nColumnNumber1Based, ResultSet resultSetSource, PreparedStatement insertStatementInsert)
{
	try
	{			
		BigDecimal value = resultSetSource.getBigDecimal(m_nColSourceIndex);
		if (!resultSetSource.wasNull())
			insertStatementInsert.setBigDecimal(m_nColSourceIndex, value);
		else
			insertStatementInsert.setNull(m_nColSourceIndex, Types.DECIMAL);			
		return true;
	}
	catch (SQLException e)
	{
		e.printStackTrace();
	}
	return false;		
}
 
Example 7
Project: oscm   File: UserQuery.java   Source Code and License Vote up 5 votes
@Override
protected void setParameters(PreparedStatement p) throws SQLException {
    long queryUserKey = 0;
    try {
        queryUserKey = Long.parseLong(userKey);
        p.setLong(1, queryUserKey);
    } catch (NumberFormatException e) {
        p.setNull(1, Types.BIGINT);
    }
}
 
Example 8
Project: sample.daytrader3   File: TradeDirect.java   Source Code and License Vote up 5 votes
private OrderDataBean createOrder(Connection conn,
		AccountDataBean accountData, QuoteDataBean quoteData,
		HoldingDataBean holdingData, String orderType, double quantity)
		throws Exception {
	OrderDataBean orderData = null;

	Timestamp currentDate = new Timestamp(System.currentTimeMillis());

	PreparedStatement stmt = getStatement(conn, createOrderSQL);

	Integer orderID = KeySequenceDirect.getNextID(conn, "order", inSession,
			getInGlobalTxn());
	stmt.setInt(1, orderID.intValue());
	stmt.setString(2, orderType);
	stmt.setString(3, "open");
	stmt.setTimestamp(4, currentDate);
	stmt.setDouble(5, quantity);
	stmt.setBigDecimal(6, quoteData.getPrice().setScale(
			FinancialUtils.SCALE, FinancialUtils.ROUND));
	stmt.setBigDecimal(7, TradeConfig.getOrderFee(orderType));
	stmt.setInt(8, accountData.getAccountID().intValue());
	if (holdingData == null)
		stmt.setNull(9, java.sql.Types.INTEGER);
	else
		stmt.setInt(9, holdingData.getHoldingID().intValue());
	stmt.setString(10, quoteData.getSymbol());
	int rowCount = stmt.executeUpdate();

	stmt.close();

	return getOrderData(conn, orderID.intValue());
}
 
Example 9
Project: adept   File: JdbcHelper.java   Source Code and License Vote up 5 votes
/**
 * 循环设置PreparedStatement的参数.
 * @param pstmt PreparedStatement实例
 * @param params 数组参数
 * @return PreparedStatement实例
 * @throws SQLException SQL异常
 */
private static PreparedStatement setParams(PreparedStatement pstmt, Object[] params) throws SQLException {
    for (int i = 0, len = params.length; i < len; i++) {
        Object param = params[i];
        if (param != null) {
            pstmt.setObject(i + 1, param);
        } else {
            pstmt.setNull(i + 1, Types.VARCHAR);
        }
    }
    return pstmt;
}
 
Example 10
Project: OpenDiabetes   File: TestSql.java   Source Code and License Vote up 5 votes
public void testAny() {

        try {
            String ddl =
                "drop table PRICE_RELATE_USER_ORDER_V2 if exists;"
                + "create table PRICE_RELATE_USER_ORDER_V2 "
                + "(ID_ORDER_V2 BIGINT, ID_USER NUMERIC, DATE_CREATE TIMESTAMP)";
            String sql = "insert into PRICE_RELATE_USER_ORDER_V2 "
                         + "(ID_ORDER_V2, ID_USER, DATE_CREATE) " + "values "
                         + "(?, ?, ?)";
            Statement st = connection.createStatement();

            st.execute(ddl);

            PreparedStatement ps = connection.prepareStatement(sql);

            ps.setLong(1, 1);
            ps.setNull(2, Types.NUMERIC);
            ps.setTimestamp(
                3, new java.sql.Timestamp(System.currentTimeMillis()));
            ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("TestSql.testAny() error: " + e.getMessage());
        }

        System.out.println("testAny complete");
    }
 
Example 11
Project: aliyun-maxcompute-data-collectors   File: JdbcWritableBridge.java   Source Code and License Vote up 5 votes
public static void writeBigDecimal(BigDecimal val, int paramIdx,
    int sqlType, PreparedStatement s) throws SQLException {
  if (null == val) {
    s.setNull(paramIdx, sqlType);
  } else {
    s.setBigDecimal(paramIdx, val);
  }
}
 
Example 12
Project: oscm   File: RoleQuery.java   Source Code and License Vote up 5 votes
@Override
protected void setParameters(PreparedStatement p) throws SQLException {
    long queryUserKey = 0;
    try {
        queryUserKey = Long.parseLong(userKey);
        p.setLong(1, queryUserKey);
    } catch (NumberFormatException e) {
        p.setNull(1, Types.BIGINT);
    }
}
 
Example 13
Project: metanome-algorithms   File: PostgreSQLDataAccessObject.java   Source Code and License Vote up 5 votes
@Override
public PreparedStatement insertValuesIntoStatement(PreparedStatement statement, String[] values, String[] valueTypes, int offset) throws NumberFormatException, SQLException {
	for (int i = 0; i < values.length; i++) {
		String valueType = valueTypes[i + offset].toLowerCase();
		
		if ((values[i] == null) || (values[i].equals("")))  {
			if (valueType.contains("long") || valueType.contains("big") || valueType.contains("int8"))
				statement.setNull(i + 1, java.sql.Types.BIGINT);
			else if (valueType.contains("int") || valueType.contains("serial"))
				statement.setNull(i + 1, java.sql.Types.INTEGER);
			else if (valueType.contains("float") || valueType.contains("numeric") || valueType.contains("decimal") || valueType.contains("real") || valueType.contains("precision"))
				statement.setNull(i + 1, java.sql.Types.FLOAT);
			else if (valueType.contains("bool"))
				statement.setNull(i + 1, java.sql.Types.BOOLEAN);
			else if (valueType.contains("date"))
				statement.setNull(i + 1, java.sql.Types.DATE);
			else 
				statement.setNull(i + 1, java.sql.Types.VARCHAR);
		}
		else {
			if (valueType.contains("long") || valueType.contains("big") || valueType.contains("int8"))
				statement.setLong(i + 1, Long.valueOf(values[i]).longValue());
			else if (valueType.contains("int") || valueType.contains("serial"))
				statement.setInt(i + 1, Integer.valueOf(values[i]).intValue());
			else if (valueType.contains("float") || valueType.contains("numeric") || valueType.contains("decimal") || valueType.contains("real") || valueType.contains("precision"))
				statement.setFloat(i + 1, Float.valueOf(values[i]).shortValue());
			else if (valueType.contains("bool"))
				statement.setBoolean(i + 1, Boolean.valueOf(values[i]).booleanValue());
			else if (valueType.contains("date"))
				statement.setDate(i + 1, Date.valueOf(values[i]));
			else 
				statement.setString(i + 1, values[i]);
		}
	}
	return statement;
}
 
Example 14
Project: morpheus-core   File: DbSink.java   Source Code and License Vote up 5 votes
@Override()
void apply(PreparedStatement stmt, int stmtIndex, DataFrameRow<R,C> row) {
    try {
        this.cursor.atRowOrdinal(row.ordinal());
        if (cursor.isNull()) {
            stmt.setNull(stmtIndex, colType.getTypeCode());
        } else {
            switch (colType) {
                case BIT:       stmt.setBoolean(stmtIndex, mapper.applyAsBoolean(cursor));          break;
                case BOOLEAN:   stmt.setBoolean(stmtIndex, mapper.applyAsBoolean(cursor));          break;
                case TINYINT:   stmt.setInt(stmtIndex, mapper.applyAsInt(cursor));                  break;
                case SMALLINT:  stmt.setInt(stmtIndex, mapper.applyAsInt(cursor));                  break;
                case FLOAT:     stmt.setDouble(stmtIndex, mapper.applyAsDouble(cursor));            break;
                case INTEGER:   stmt.setInt(stmtIndex, mapper.applyAsInt(cursor));                  break;
                case BIGINT:    stmt.setLong(stmtIndex, mapper.applyAsLong(cursor));                break;
                case DOUBLE:    stmt.setDouble(stmtIndex, mapper.applyAsDouble(cursor));            break;
                case DECIMAL:   stmt.setDouble(stmtIndex, mapper.applyAsDouble(cursor));            break;
                case VARCHAR:   stmt.setString(stmtIndex, (String)mapper.apply(cursor));            break;
                case DATE:      stmt.setDate(stmtIndex, (Date)mapper.apply(cursor));                break;
                case TIME:      stmt.setTime(stmtIndex, (Time)mapper.apply(cursor));                break;
                case DATETIME:  stmt.setTimestamp(stmtIndex, (Timestamp)mapper.apply(cursor));      break;
                default:    throw new IllegalStateException("Unsupported column type:" + colType);
            }
        }
    } catch (Exception ex) {
        final String coordinates = String.format("(%s, %s)", cursor.rowKey(), cursor.colKey());
        throw new DataFrameException("Failed to apply value to SQL statement at " + coordinates, ex);
    }
}
 
Example 15
Project: aliyun-maxcompute-data-collectors   File: JdbcWritableBridge.java   Source Code and License Vote up 5 votes
public static void writeDate(Date val, int paramIdx, int sqlType,
    PreparedStatement s) throws SQLException {
  if (null == val) {
    s.setNull(paramIdx, sqlType);
  } else {
    s.setDate(paramIdx, val);
  }
}
 
Example 16
Project: Equella   File: ImmutableHibernateXStreamType.java   Source Code and License Vote up 5 votes
@Override
public void nullSafeSet(PreparedStatement st, Object value, int index) throws SQLException
{
	if( value != null )
	{
		String string = xstream.serialiseToXml(value);
		StringReader reader = new StringReader(string);
		st.setCharacterStream(index, reader, string.length());
	}
	else
	{
		st.setNull(index, sqlTypes()[0]);
	}
}
 
Example 17
Project: Nird2   File: BasicH2Test.java   Source Code and License Vote up 5 votes
private void insertRow(byte[] id, String name) throws SQLException {
	String sql = "INSERT INTO foo (uniqueId, name) VALUES (?, ?)";
	try {
		PreparedStatement ps = connection.prepareStatement(sql);
		if (id == null) ps.setNull(1, BINARY);
		else ps.setBytes(1, id);
		ps.setString(2, name);
		int affected = ps.executeUpdate();
		assertEquals(1, affected);
		ps.close();
	} catch (SQLException e) {
		connection.close();
		throw e;
	}
}
 
Example 18
Project: redesocial   File: UsuarioDAO.java   Source Code and License Vote up 5 votes
/**
* Método responsável pela inserção de um objeto no banco de dados na tabela usuários
* @param dto objeto com os dados de usuário já preenchido
* @throws Exception
*/
@Override
public void inserir(Usuario dto) throws Exception {
    Connection conexao = getConexao();
    
    PreparedStatement pstmt = conexao.prepareStatement("insert into usuarios(nome, email, telefone, senha, data_nascimento, sexo, data_cadastro, status, foto, cidade) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
    
    pstmt.setString(1, dto.getNome());
    pstmt.setString(2, dto.getEmail());
    pstmt.setString(3, dto.getTelefone());
    pstmt.setString(4, dto.getSenha());
    pstmt.setDate(5, new java.sql.Date(dto.getDataNascimento().getTime()));
    pstmt.setString(6, String.valueOf(dto.getSexo().getId()));
    pstmt.setDate(7, new java.sql.Date(dto.getDataCadastro().getTime()));
    pstmt.setBoolean(8, dto.getStatus());
    
    if (dto.getFoto() != null){
        pstmt.setInt(9, dto.getFoto().getId());
    } else {
        pstmt.setNull(9, Types.BLOB);
    }
    
    
    pstmt.setInt(10, dto.getCidade().getId()); 
   
    /**
  * executa uma inserção
  */
    pstmt.executeUpdate();
    
    dto.setId(getId(pstmt));
}
 
Example 19
Project: OpenVertretung   File: StatementRegressionTest.java   Source Code and License Vote up 5 votes
public void testBug5510() throws Exception {
    // This is a server bug that should be fixed by 4.1.6
    if (versionMeetsMinimum(4, 1, 6)) {
        createTable("`testBug5510`",
                "(`a` bigint(20) NOT NULL auto_increment, `b` varchar(64) default NULL, `c` varchar(64) default NULL,"
                        + "`d` varchar(255) default NULL, `e` int(11) default NULL, `f` varchar(32) default NULL, `g` varchar(32) default NULL,"
                        + "`h` varchar(80) default NULL, `i` varchar(255) default NULL, `j` varchar(255) default NULL, `k` varchar(255) default NULL,"
                        + "`l` varchar(32) default NULL, `m` varchar(32) default NULL, `n` timestamp NOT NULL default CURRENT_TIMESTAMP on update"
                        + " CURRENT_TIMESTAMP, `o` int(11) default NULL, `p` int(11) default NULL, PRIMARY KEY  (`a`)) DEFAULT CHARSET=latin1",
                "InnoDB ");
        PreparedStatement pStmt = this.conn.prepareStatement("INSERT INTO testBug5510 (a) VALUES (?)");
        pStmt.setNull(1, 0);
        pStmt.executeUpdate();
    }
}
 
Example 20
Project: rapidminer   File: DatabaseHandler.java   Source Code and License Vote up 4 votes
private void applyBatchInsertIntoTable(PreparedStatement statement, Example example, Iterator<AttributeRole> attributes, boolean addAutoGeneratedPrimaryKeys, Attribute genPrimaryKey) throws SQLException {
    LinkedList attributeList = new LinkedList();

    while(attributes.hasNext()) {
        attributeList.add(((AttributeRole)attributes.next()).getAttribute());
    }

    int counter = 1;
    Iterator var8 = attributeList.iterator();

    while(true) {
        Attribute attribute;
        do {
            if(!var8.hasNext()) {
                statement.addBatch();
                return;
            }

            attribute = (Attribute)var8.next();
        } while(addAutoGeneratedPrimaryKeys && attribute == genPrimaryKey);

        double value = example.getValue(attribute);
        if(Double.isNaN(value)) {
            int valueString = this.statementCreator.getSQLTypeForRMValueType(attribute.getValueType()).getDataType();
            statement.setNull(counter, valueString);
        } else if(attribute.isNominal()) {
            String var13 = attribute.getMapping().mapIndex((int)value);
            statement.setString(counter, var13);
        } else if(Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), 9)) {
            if(Ontology.ATTRIBUTE_VALUE_TYPE.isA(attribute.getValueType(), 11)) {
                statement.setTime(counter, new Time((long)value));
            } else {
                statement.setTimestamp(counter, new Timestamp((long)value));
            }
        } else {
            statement.setDouble(counter, value);
        }

        ++counter;
    }
}