當前位置: 首頁>>代碼示例>>Java>>正文


Java PreparedStatement.setObject方法代碼示例

本文整理匯總了Java中java.sql.PreparedStatement.setObject方法的典型用法代碼示例。如果您正苦於以下問題:Java PreparedStatement.setObject方法的具體用法?Java PreparedStatement.setObject怎麽用?Java PreparedStatement.setObject使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在java.sql.PreparedStatement的用法示例。


在下文中一共展示了PreparedStatement.setObject方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: update

import java.sql.PreparedStatement; //導入方法依賴的package包/類
/**
 * 傳入的SQL語句隻能是INSERT,DELETE,UPDATE和DDL語句
 *
 * @param sql 相應SQL語句
 * @param arg 傳入的占位符的參數
 */
public static void update(String sql, Object... arg) {
    Connection connection = JDBCUtils.getConnection();
    PreparedStatement ps = null;
    try {
        ps = connection.prepareStatement(sql);
        for (int i = 0; i < arg.length; i++) {
            ps.setObject(i + 1, arg[i]);
        }
        ps.executeUpdate();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    JDBCUtils.release(ps, connection);
}
 
開發者ID:FlyingHe,項目名稱:UtilsMaven,代碼行數:23,代碼來源:DBUtils.java

示例2: updateBatch

import java.sql.PreparedStatement; //導入方法依賴的package包/類
/**
 * 該方法用於批處理,當需要一次執行多條相同SQL語句時使用該方法時效率較高
 *
 * @param sql 需要執行的SQL語句
 * @param arg 傳入SQL語句所需要的占位符參數,下標均從0開始,每個一維下標對應於SQL語句的一組占位符參數
 */
public static void updateBatch(String sql, Object[][] arg) {
    Connection connection = JDBCUtils.getConnection();
    PreparedStatement ps = null;
    try {
        ps = connection.prepareStatement(sql);
        for (int i = 0; i < arg.length; i++) {
            for (int j = 0; j < arg[i].length; j++) {
                ps.setObject(j + 1, arg[i][j]);
            }
            ps.addBatch();
        }
        ps.executeBatch();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    JDBCUtils.release(ps, connection);
}
 
開發者ID:FlyingHe,項目名稱:UtilsMaven,代碼行數:26,代碼來源:DBUtils.java

示例3: insertTestDataOffsetDTTypes

import java.sql.PreparedStatement; //導入方法依賴的package包/類
/**
 * Helper method for *SetObject* tests.
 * Insert data into the given PreparedStatement, or any of its subclasses, with the following structure:
 * 1 - `id` INT
 * 2 - `ot1` VARCHAR
 * 3 - `ot2` BLOB
 * 4 - `odt1` VARCHAR
 * 5 - `odt2` BLOB
 * 
 * @param pstmt
 * @return the row count of inserted records.
 * @throws Exception
 */
private int insertTestDataOffsetDTTypes(PreparedStatement pstmt) throws Exception {
    pstmt.setInt(1, 1);
    pstmt.setObject(2, testOffsetTime, JDBCType.VARCHAR);
    pstmt.setObject(3, testOffsetTime);
    pstmt.setObject(4, testOffsetDateTime, JDBCType.VARCHAR);
    pstmt.setObject(5, testOffsetDateTime);
    assertEquals(1, pstmt.executeUpdate());

    if (pstmt instanceof CallableStatement) {
        CallableStatement cstmt = (CallableStatement) pstmt;

        cstmt.setInt("id", 2);
        cstmt.setObject("ot1", testOffsetTime, JDBCType.VARCHAR);
        cstmt.setObject("ot2", testOffsetTime);
        cstmt.setObject("odt1", testOffsetDateTime, JDBCType.VARCHAR);
        cstmt.setObject("odt2", testOffsetDateTime);
        assertEquals(1, cstmt.executeUpdate());

        return 2;
    }

    return 1;
}
 
開發者ID:Jugendhackt,項目名稱:OpenVertretung,代碼行數:37,代碼來源:StatementsTest.java

示例4: setParam

import java.sql.PreparedStatement; //導入方法依賴的package包/類
public void setParam(PreparedStatement ps, int parameterIndex,
                     Object object) throws SQLException {
    if (object instanceof Timestamp) {
        ps.setTimestamp(parameterIndex, (Timestamp) object);
    } else if (object instanceof Date) {
        ps.setDate(parameterIndex, (Date) object);
    } else if (object instanceof String) {
        ps.setString(parameterIndex, (String) object);
    } else if (object instanceof Integer) {
        ps.setInt(parameterIndex, ((Integer) object).intValue());
    } else if (object instanceof Long) {
        ps.setLong(parameterIndex, ((Long) object).longValue());
    } else if (object instanceof Boolean) {
        ps.setBoolean(parameterIndex, ((Boolean) object).booleanValue());
    } else {
        ps.setObject(parameterIndex, object);
    }
}
 
開發者ID:Vitaliy-Yakovchuk,項目名稱:ramus,代碼行數:19,代碼來源:JDBCTemplate.java

示例5: testBug1901

import java.sql.PreparedStatement; //導入方法依賴的package包/類
/**
 * Tests fix for BUG#1901 -- PreparedStatement.setObject(int, Object, int,
 * int) doesn't support CLOB or BLOB types.
 * 
 * @throws Exception
 *             if this test fails for any reason
 */
public void testBug1901() throws Exception {
    try {
        this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1901");
        this.stmt.executeUpdate("CREATE TABLE testBug1901 (field1 VARCHAR(255))");
        this.stmt.executeUpdate("INSERT INTO testBug1901 VALUES ('aaa')");

        this.rs = this.stmt.executeQuery("SELECT field1 FROM testBug1901");
        this.rs.next();

        Clob valueAsClob = this.rs.getClob(1);
        Blob valueAsBlob = this.rs.getBlob(1);

        PreparedStatement pStmt = this.conn.prepareStatement("INSERT INTO testBug1901 VALUES (?)");
        pStmt.setObject(1, valueAsClob, java.sql.Types.CLOB, 0);
        pStmt.executeUpdate();
        pStmt.setObject(1, valueAsBlob, java.sql.Types.BLOB, 0);
        pStmt.executeUpdate();
    } finally {
        this.stmt.executeUpdate("DROP TABLE IF EXISTS testBug1901");
    }
}
 
開發者ID:JuanJoseFJ,項目名稱:ProyectoPacientes,代碼行數:29,代碼來源:StatementRegressionTest.java

示例6: getCount

import java.sql.PreparedStatement; //導入方法依賴的package包/類
protected long getCount(Object conditionObj, Connection conn) {

		Class<?> clz = conditionObj.getClass();

		String sql = MapperFactory.getSql(clz, Mapper.PAGINATION);

		Parsed parsed = Parser.get(clz);

		Map<String, Object> queryMap = BeanUtilX.getQueryMap(parsed, conditionObj);
		sql = SqlUtil.concat(parsed, sql, queryMap);

		String countSql = sql.replace(X.PAGINATION, "COUNT(*) count");

		long count = 0;
		PreparedStatement pstmt = null;
		try {
			conn.setAutoCommit(true);
			pstmt = conn.prepareStatement(countSql);

			int i = 1;
			for (Object o : queryMap.values()) {
				pstmt.setObject(i++, o);
			}

			ResultSet rs = pstmt.executeQuery();

			if (rs.next()) {
				count = rs.getLong("count");
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(pstmt);
			close(conn);
		}

		return count;
	}
 
開發者ID:x7-framework,項目名稱:x7,代碼行數:40,代碼來源:DaoImpl.java

示例7: execute

import java.sql.PreparedStatement; //導入方法依賴的package包/類
public Integer execute(Connection connection, String table) throws SQLException {
    int index = 1;
    PreparedStatement preparedStatement = connection.prepareStatement(generateSqlString(table));

    for (int i = 0; i < columnsToUpdate.size(); i++) {
        preparedStatement.setObject(index++, valuesToUpdate.get(i));
    }

    for (int i = 0; i < columnsToCheck.size(); i++) {
        preparedStatement.setObject(index++, valuesToCheck.get(i));
    }

    System.out.println(preparedStatement);
    return preparedStatement.executeUpdate();
}
 
開發者ID:shawlaf,項目名稱:Banmanager,代碼行數:16,代碼來源:DatabaseUpdate.java

示例8: getSingleValue

import java.sql.PreparedStatement; //導入方法依賴的package包/類
public Object getSingleValue(String sql, Object... args)
{
	Object value = null;
	Connection connection = null;
	PreparedStatement preparedStatement = null;
	ResultSet resultSet = null;

	try
	{
		connection = JDBCTools.getConnection();
		preparedStatement = connection.prepareStatement(sql);

		if(args!=null)
		{
			for (int i = 0; i < args.length; i++)
			{
				preparedStatement.setObject(i + 1, args[i]);
			}
		}

		resultSet = preparedStatement.executeQuery();
		if (resultSet.next())
		{
			value = resultSet.getObject(1);
		}
	} catch (Exception e)
	{
		e.printStackTrace();
	} finally
	{
		JDBCTools.releaseConnection(connection,preparedStatement,resultSet);
	}

	return value;
}
 
開發者ID:yanhanwen,項目名稱:DrugStoreManagement,代碼行數:36,代碼來源:BaseDao.java

示例9: fill

import java.sql.PreparedStatement; //導入方法依賴的package包/類
@Override
public void fill(PreparedStatement ps, int column, String value)
        throws SQLException {
    if (value == null)
        ps.setObject(column, null);
    else
        ps.setLong(column, Long.parseLong(value));
}
 
開發者ID:Vitaliy-Yakovchuk,項目名稱:ramus,代碼行數:9,代碼來源:XMLToTable.java

示例10: adpterSqlKey

import java.sql.PreparedStatement; //導入方法依賴的package包/類
protected static void adpterSqlKey(PreparedStatement pstmt, String keyOne, String keyTwo, Object obj, int i) throws SQLException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
	/*
	 * 處理KEY
	 */
	Method method = null;
	try {
		method = obj.getClass().getDeclaredMethod(BeanUtil.getGetter(keyOne));
	} catch (NoSuchMethodException e) {
		method = obj.getClass().getSuperclass()
				.getDeclaredMethod(BeanUtil.getGetter(keyOne));
	}
	Object value = method.invoke(obj);
	pstmt.setObject(i++, value);

}
 
開發者ID:x7-framework,項目名稱:x7,代碼行數:16,代碼來源:SqlUtil.java

示例11: nullSafeSet

import java.sql.PreparedStatement; //導入方法依賴的package包/類
public void nullSafeSet(
        PreparedStatement st,
        Object value,
        int index,
        SharedSessionContractImplementor session)
        throws HibernateException, SQLException {
    if (value == null) {
        st.setNull(index, Types.OTHER);
    } else {
        st.setObject(index, value.toString(), Types.OTHER);
    }
}
 
開發者ID:vladmihalcea,項目名稱:hibernate-types,代碼行數:13,代碼來源:PostgreSQLEnumType.java

示例12: getStats

import java.sql.PreparedStatement; //導入方法依賴的package包/類
private void getStats(MongoObject mongoObject, String sourceDbName, String sourceSchemaName) throws SyncError {
	SelectQueryBuilder queryBuilder = new SelectQueryBuilder();
	List<MatchAble> bindvalues = new ArrayList<MatchAble>();
	PreparedStatement stmt = null;
	ResultSet rs = null;
	String countQuery = queryBuilder.select().from(mongoObject.getSourceTables().get(0))
			.where(mongoObject.getFilters()).getCountQuery(bindvalues);
	Connection connection = null;
	try {
		connection = DBCacheManager.INSTANCE.getCachedOracleConnection(sourceDbName, sourceSchemaName);
		stmt = connection.prepareStatement(countQuery);
		if (bindvalues != null) {
			for (int index = 0; index < bindvalues.size(); index++) {
				stmt.setObject(index + 1, bindvalues.get(index).getSqlExpressionForMatchable());
			}
		}
		rs = stmt.executeQuery();
		logger.debug("Query Executed to get RowCount");
		rs.next();
		int totalRows = rs.getInt(1);
		logger.info("Rowcount Fecthed : " + totalRows);
		marker.setTotalRows(totalRows);
	} catch (SQLException e) {
		logger.error("Error while getting total count of rows to be processed", e);
		throw new SyncError(e);
	} finally {
		DbResourceUtils.closeResources(rs, stmt, connection);
	}
}
 
開發者ID:gagoyal01,項目名稱:mongodb-rdbms-sync,代碼行數:30,代碼來源:OracleToMongoEvent.java

示例13: getStats

import java.sql.PreparedStatement; //導入方法依賴的package包/類
@SuppressWarnings("rawtypes")
private void getStats(OracleToMongoGridFsMap map) throws SyncError {
	SelectQueryBuilder queryBuilder = new SelectQueryBuilder();
	List<MatchAble> bindvalues = new ArrayList<MatchAble>();
	PreparedStatement stmt = null;
	ResultSet rs = null;

	String countQuery = queryBuilder.select().from(map.getStreamTable()).where(map.getFilters())
			.getCountQuery(bindvalues);
	Connection connection = null;
	try {
		connection = DBCacheManager.INSTANCE.getCachedOracleConnection(map.getSourceDbName(),
				map.getSourceUserName());
		stmt = connection.prepareStatement(countQuery);
		if (bindvalues != null) {
			for (int index = 0; index < bindvalues.size(); index++) {
				stmt.setObject(index + 1, bindvalues.get(index).getSqlExpressionForMatchable());
			}
		}
		rs = stmt.executeQuery();
		logger.debug("Query Executed to get RowCount");
		rs.next();
		int totalRows = rs.getInt(1);
		logger.info("Rowcount Fecthed : " + totalRows);
		marker.setTotalRows(totalRows);
	} catch (SQLException e) {
		logger.error("Error while getting total count of rows to be processed", e);
		throw new SyncError(e);
	} finally {
		DbResourceUtils.closeResources(rs, stmt, connection);
	}
}
 
開發者ID:gagoyal01,項目名稱:mongodb-rdbms-sync,代碼行數:33,代碼來源:OracleToMongoGridFsEvent.java

示例14: getValueOfCertainColumnOfAllRecord

import java.sql.PreparedStatement; //導入方法依賴的package包/類
/**
 * 用於查詢SQL語句中返回的所有記錄中的第一個字段的值,適用於多條記錄單個字段的查詢,將每條記錄的該字段存入List中
 *
 * @param sql 查詢SQL語句
 * @param arg 傳入的占位符的參數
 * @return 返回查詢到的所有記錄的第一個字段的值,若沒有符合條件的記錄,則返回空List
 */
@SuppressWarnings("unchecked")
public static <T> List<T> getValueOfCertainColumnOfAllRecord(String sql, Object... arg) {
    Connection connection = JDBCUtils.getConnection();
    PreparedStatement ps = null;

    ResultSet result = null;
    List<T> list = new ArrayList<T>();// 存放查詢到的記錄的字段的值
    try {
        ps = connection.prepareStatement(sql);
        // 填充占位符
        for (int i = 0; i < arg.length; i++) {
            ps.setObject(i + 1, arg[i]);
        }
        // 獲取結果集
        result = ps.executeQuery();
        // 循環遍曆結果集中的記錄,並將每條記錄的第一個字段放入List中
        while (result.next()) {
            list.add((T) result.getObject(1));
        }

    } catch (SQLException e) {
        e.printStackTrace();
    } finally {

        JDBCUtils.release(result, ps, connection);
    }

    return list;
}
 
開發者ID:FlyingHe,項目名稱:UtilsMaven,代碼行數:37,代碼來源:DBUtils.java

示例15: testBug5136

import java.sql.PreparedStatement; //導入方法依賴的package包/類
/**
 * Tests for BUG#5136, GEOMETRY types getting corrupted, turns out to be a
 * server bug.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug5136() throws Exception {
    if (!this.DISABLED_testBug5136) {
        PreparedStatement toGeom = this.conn.prepareStatement("select GeomFromText(?)");
        PreparedStatement toText = this.conn.prepareStatement("select AsText(?)");

        String inText = "POINT(146.67596278 -36.54368233)";

        // First assert that the problem is not at the server end
        this.rs = this.stmt.executeQuery("select AsText(GeomFromText('" + inText + "'))");
        this.rs.next();

        String outText = this.rs.getString(1);
        this.rs.close();
        assertTrue("Server side only\n In: " + inText + "\nOut: " + outText, inText.equals(outText));

        // Now bring a binary geometry object to the client and send it back
        toGeom.setString(1, inText);
        this.rs = toGeom.executeQuery();
        this.rs.next();

        // Return a binary geometry object from the WKT
        Object geom = this.rs.getObject(1);
        this.rs.close();
        toText.setObject(1, geom);
        this.rs = toText.executeQuery();
        this.rs.next();

        // Return WKT from the binary geometry
        outText = this.rs.getString(1);
        this.rs.close();
        assertTrue("Server to client and back\n In: " + inText + "\nOut: " + outText, inText.equals(outText));
    }
}
 
開發者ID:bragex,項目名稱:the-vigilantes,代碼行數:41,代碼來源:ResultSetRegressionTest.java


注:本文中的java.sql.PreparedStatement.setObject方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。