当前位置: 首页>>代码示例>>Java>>正文


Java PreparedStatement类代码示例

本文整理汇总了Java中com.datastax.driver.core.PreparedStatement的典型用法代码示例。如果您正苦于以下问题:Java PreparedStatement类的具体用法?Java PreparedStatement怎么用?Java PreparedStatement使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


PreparedStatement类属于com.datastax.driver.core包,在下文中一共展示了PreparedStatement类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getPropertiesValueById

import com.datastax.driver.core.PreparedStatement; //导入依赖的package包/类
@Override
public Response getPropertiesValueById(String keyspaceName, String tableName, String id,
    String... properties) {
  long startTime = System.currentTimeMillis();
  ProjectLogger.log("Cassandra Service getPropertiesValueById method started at ==" + startTime,
      LoggerEnum.PERF_LOG);
  Response response = new Response();
  try {
    String selectQuery = CassandraUtil.getSelectStatement(keyspaceName, tableName, properties);
    PreparedStatement statement = connectionManager.getSession(keyspaceName).prepare(selectQuery);
    BoundStatement boundStatement = new BoundStatement(statement);
    ResultSet results =
        connectionManager.getSession(keyspaceName).execute(boundStatement.bind(id));
    response = CassandraUtil.createResponse(results);
  } catch (Exception e) {
    ProjectLogger.log(Constants.EXCEPTION_MSG_FETCH + tableName + " : " + e.getMessage(), e);
    throw new ProjectCommonException(ResponseCode.SERVER_ERROR.getErrorCode(),
        ResponseCode.SERVER_ERROR.getErrorMessage(), ResponseCode.SERVER_ERROR.getResponseCode());
  }
  long stopTime = System.currentTimeMillis();
  long elapsedTime = stopTime - startTime;
  ProjectLogger.log("Cassandra Service getPropertiesValueById method end at ==" + stopTime
      + " ,Total time elapsed = " + elapsedTime, LoggerEnum.PERF_LOG);
  return response;
}
 
开发者ID:project-sunbird,项目名称:sunbird-utils,代码行数:26,代码来源:CassandraOperationImpl.java

示例2: tuneStatementExecutionOptions

import com.datastax.driver.core.PreparedStatement; //导入依赖的package包/类
/**
 * Tunes CQL statement execution options (consistency level, fetch option and etc.).
 *
 * @param statement Statement.
 * @return Modified statement.
 */
private Statement tuneStatementExecutionOptions(Statement statement) {
    String qry = "";
    if (statement instanceof BoundStatement) {
        qry = ((BoundStatement)statement).preparedStatement().getQueryString().trim().toLowerCase();
    }
    else if (statement instanceof PreparedStatement) {
        qry = ((PreparedStatement)statement).getQueryString().trim().toLowerCase();
    }
    boolean readStatement = qry.startsWith("select");
    boolean writeStatement = statement instanceof Batch || statement instanceof BatchStatement ||
        qry.startsWith("insert") || qry.startsWith("delete") || qry.startsWith("update");
    if (readStatement && readConsistency != null) {
        statement.setConsistencyLevel(readConsistency);
    }
    if (writeStatement && writeConsistency != null) {
        statement.setConsistencyLevel(writeConsistency);
    }
    if (fetchSize != null) {
        statement.setFetchSize(fetchSize);
    }
    return statement;
}
 
开发者ID:epam,项目名称:Lagerta,代码行数:29,代码来源:CassandraSessionImpl.java

示例3: bindKeyValue

import com.datastax.driver.core.PreparedStatement; //导入依赖的package包/类
/**
 * Binds Ignite cache key and value object to {@link PreparedStatement}.
 *
 * @param statement statement to which key and value object should be bind.
 * @param key key object.
 * @param val value object.
 * @return statement with bounded key and value.
 */
public BoundStatement bindKeyValue(PreparedStatement statement, Object key, Object val) {
    KeyPersistenceSettings keySettings = persistenceSettings.getKeyPersistenceSettings();
    Object[] keyValues = getBindingValues(keySettings.getStrategy(),
        keySettings.getSerializer(), keySettings.getFields(), key);
    ValuePersistenceSettings valSettings = persistenceSettings.getValuePersistenceSettings();
    Object[] valValues = getBindingValues(valSettings.getStrategy(),
        valSettings.getSerializer(), valSettings.getFields(), val);
    Object[] values = new Object[keyValues.length + valValues.length];
    int i = 0;
    for (Object keyVal : keyValues) {
        values[i] = keyVal;
        i++;
    }
    for (Object valVal : valValues) {
        values[i] = valVal;
        i++;
    }
    return statement.bind(values);
}
 
开发者ID:epam,项目名称:Lagerta,代码行数:28,代码来源:PersistenceController.java

示例4: main

import com.datastax.driver.core.PreparedStatement; //导入依赖的package包/类
public static void main(String[] args) {

		Session session = Connection.connect();		
		PreparedStatement preparedStatement = session.prepare("insert into user (id, name, age) values (?, ?, ?)");

		try {
			BoundStatement boundStatement = preparedStatement.bind(UUIDs.timeBased(), "Hector", 34);
			ResultSet rs = session.execute(boundStatement);
			System.out.println(rs);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		
		Connection.close();

	}
 
开发者ID:abulbasar,项目名称:cassandra-java-driver-examples,代码行数:17,代码来源:PreparedStatementExample.java

示例5: main

import com.datastax.driver.core.PreparedStatement; //导入依赖的package包/类
public static void main(String[] args) {

		Session session = Connection.connect();		
		BatchStatement batchStatement = new BatchStatement();
		
		PreparedStatement preparedStatement = session.prepare("insert into user (id, name) values (?, ?)");
		int i = 0;
		while(i < 10) {
			batchStatement.add(preparedStatement.bind(UUIDs.timeBased(), "user-" + i));
			++i;
		}

		try {
			ResultSet rs = session.execute(batchStatement);
			System.out.println(rs);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		Connection.close();

	}
 
开发者ID:abulbasar,项目名称:cassandra-java-driver-examples,代码行数:22,代码来源:BatchStatementExample.java

示例6: getSaveStmt

import com.datastax.driver.core.PreparedStatement; //导入依赖的package包/类
private PreparedStatement getSaveStmt() {
    if (saveStmt == null) {
        saveStmt = getSession().prepare("INSERT INTO " + ModelConstants.ATTRIBUTES_KV_CF +
                "(" + ENTITY_TYPE_COLUMN +
                "," + ENTITY_ID_COLUMN +
                "," + ATTRIBUTE_TYPE_COLUMN +
                "," + ATTRIBUTE_KEY_COLUMN +
                "," + LAST_UPDATE_TS_COLUMN +
                "," + ModelConstants.STRING_VALUE_COLUMN +
                "," + ModelConstants.BOOLEAN_VALUE_COLUMN +
                "," + ModelConstants.LONG_VALUE_COLUMN +
                "," + ModelConstants.DOUBLE_VALUE_COLUMN +
                ")" +
                " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)");
    }
    return saveStmt;
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:18,代码来源:CassandraBaseAttributesDao.java

示例7: getFetchChunksAsyncFunction

import com.datastax.driver.core.PreparedStatement; //导入依赖的package包/类
private AsyncFunction<List<Long>, List<ResultSet>> getFetchChunksAsyncFunction(EntityId entityId, String key, Aggregation aggregation, long startTs, long endTs) {
    return partitions -> {
        try {
            PreparedStatement proto = getFetchStmt(aggregation);
            List<ResultSetFuture> futures = new ArrayList<>(partitions.size());
            for (Long partition : partitions) {
                log.trace("Fetching data for partition [{}] for entityType {} and entityId {}", partition, entityId.getEntityType(), entityId.getId());
                BoundStatement stmt = proto.bind();
                stmt.setString(0, entityId.getEntityType().name());
                stmt.setUUID(1, entityId.getId());
                stmt.setString(2, key);
                stmt.setLong(3, partition);
                stmt.setLong(4, startTs);
                stmt.setLong(5, endTs);
                log.debug("Generated query [{}] for entityType {} and entityId {}", stmt, entityId.getEntityType(), entityId.getId());
                futures.add(executeAsyncRead(stmt));
            }
            return Futures.allAsList(futures);
        } catch (Throwable e) {
            log.error("Failed to fetch data", e);
            throw e;
        }
    };
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:25,代码来源:CassandraBaseTimeseriesDao.java

示例8: getSaveStmt

import com.datastax.driver.core.PreparedStatement; //导入依赖的package包/类
private PreparedStatement getSaveStmt(DataType dataType) {
    if (saveStmts == null) {
        saveStmts = new PreparedStatement[DataType.values().length];
        for (DataType type : DataType.values()) {
            saveStmts[type.ordinal()] = getSession().prepare("INSERT INTO " + ModelConstants.TS_KV_CF +
                    "(" + ModelConstants.ENTITY_TYPE_COLUMN +
                    "," + ModelConstants.ENTITY_ID_COLUMN +
                    "," + ModelConstants.KEY_COLUMN +
                    "," + ModelConstants.PARTITION_COLUMN +
                    "," + ModelConstants.TS_COLUMN +
                    "," + getColumnName(type) + ")" +
                    " VALUES(?, ?, ?, ?, ?, ?)");
        }
    }
    return saveStmts[dataType.ordinal()];
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:17,代码来源:CassandraBaseTimeseriesDao.java

示例9: getSaveTtlStmt

import com.datastax.driver.core.PreparedStatement; //导入依赖的package包/类
private PreparedStatement getSaveTtlStmt(DataType dataType) {
    if (saveTtlStmts == null) {
        saveTtlStmts = new PreparedStatement[DataType.values().length];
        for (DataType type : DataType.values()) {
            saveTtlStmts[type.ordinal()] = getSession().prepare("INSERT INTO " + ModelConstants.TS_KV_CF +
                    "(" + ModelConstants.ENTITY_TYPE_COLUMN +
                    "," + ModelConstants.ENTITY_ID_COLUMN +
                    "," + ModelConstants.KEY_COLUMN +
                    "," + ModelConstants.PARTITION_COLUMN +
                    "," + ModelConstants.TS_COLUMN +
                    "," + getColumnName(type) + ")" +
                    " VALUES(?, ?, ?, ?, ?, ?) USING TTL ?");
        }
    }
    return saveTtlStmts[dataType.ordinal()];
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:17,代码来源:CassandraBaseTimeseriesDao.java

示例10: getFetchStmt

import com.datastax.driver.core.PreparedStatement; //导入依赖的package包/类
private PreparedStatement getFetchStmt(Aggregation aggType) {
    if (fetchStmts == null) {
        fetchStmts = new PreparedStatement[Aggregation.values().length];
        for (Aggregation type : Aggregation.values()) {
            if (type == Aggregation.SUM && fetchStmts[Aggregation.AVG.ordinal()] != null) {
                fetchStmts[type.ordinal()] = fetchStmts[Aggregation.AVG.ordinal()];
            } else if (type == Aggregation.AVG && fetchStmts[Aggregation.SUM.ordinal()] != null) {
                fetchStmts[type.ordinal()] = fetchStmts[Aggregation.SUM.ordinal()];
            } else {
                fetchStmts[type.ordinal()] = getSession().prepare("SELECT " +
                        String.join(", ", ModelConstants.getFetchColumnNames(type)) + " FROM " + ModelConstants.TS_KV_CF
                        + " WHERE " + ModelConstants.ENTITY_TYPE_COLUMN + " = ? "
                        + "AND " + ModelConstants.ENTITY_ID_COLUMN + " = ? "
                        + "AND " + ModelConstants.KEY_COLUMN + " = ? "
                        + "AND " + ModelConstants.PARTITION_COLUMN + " = ? "
                        + "AND " + ModelConstants.TS_COLUMN + " > ? "
                        + "AND " + ModelConstants.TS_COLUMN + " <= ?"
                        + (type == Aggregation.NONE ? " ORDER BY " + ModelConstants.TS_COLUMN + " DESC LIMIT ?" : ""));
            }
        }
    }
    return fetchStmts[aggType.ordinal()];
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:24,代码来源:CassandraBaseTimeseriesDao.java

示例11: getFindLatestStmt

import com.datastax.driver.core.PreparedStatement; //导入依赖的package包/类
private PreparedStatement getFindLatestStmt() {
    if (findLatestStmt == null) {
        findLatestStmt = getSession().prepare("SELECT " +
                ModelConstants.KEY_COLUMN + "," +
                ModelConstants.TS_COLUMN + "," +
                ModelConstants.STRING_VALUE_COLUMN + "," +
                ModelConstants.BOOLEAN_VALUE_COLUMN + "," +
                ModelConstants.LONG_VALUE_COLUMN + "," +
                ModelConstants.DOUBLE_VALUE_COLUMN + " " +
                "FROM " + ModelConstants.TS_KV_LATEST_CF + " " +
                "WHERE " + ModelConstants.ENTITY_TYPE_COLUMN + " = ? " +
                "AND " + ModelConstants.ENTITY_ID_COLUMN + " = ? " +
                "AND " + ModelConstants.KEY_COLUMN + " = ? ");
    }
    return findLatestStmt;
}
 
开发者ID:osswangxining,项目名称:iotplatform,代码行数:17,代码来源:CassandraBaseTimeseriesDao.java

示例12: prepareStatement

import com.datastax.driver.core.PreparedStatement; //导入依赖的package包/类
private PreparedStatement prepareStatement() {
List<ColumnMetadata> partkeys = cluster.getMetadata().getKeyspace(keyspaceName).getTable(tableName).getPartitionKey();
StringBuilder sb = new StringBuilder();
sb.append("SELECT COUNT(*) FROM ");
sb.append(keyspaceName).append(".").append(tableName);
sb.append(" WHERE Token(");
sb.append(partkeys.get(0).getName());
for (int i = 1; i < partkeys.size(); i++)
    sb.append(", ").append(partkeys.get(i).getName());
sb.append(") > ? AND Token(");
sb.append(partkeys.get(0).getName());
for (int i = 1; i < partkeys.size(); i++)
    sb.append(",").append(partkeys.get(i).getName());
sb.append(") <= ?");

debugPrint("Query: " + sb.toString(), true, 2);

return session.prepare(sb.toString()).setConsistencyLevel(consistencyLevel);
   }
 
开发者ID:brianmhess,项目名称:cassandra-count,代码行数:20,代码来源:CqlCount.java

示例13: CassandraConfigDb

import com.datastax.driver.core.PreparedStatement; //导入依赖的package包/类
public CassandraConfigDb(List<String> contactPoints, int port) {
	
	this.contactPoints = new ArrayList<InetAddress> (contactPoints.size());
	
	for (String contactPoint : contactPoints) {
		try {
			this.contactPoints.add(InetAddress.getByName(contactPoint));
		} catch (UnknownHostException e) {
               throw new IllegalArgumentException(e.getMessage());
		}
	}
	
	this.port = port;
	
	cluster = (new Cluster.Builder()).withPort (this.port)
			.addContactPoints(this.contactPoints)
			.withSocketOptions(new SocketOptions().setReadTimeoutMillis(60000).setKeepAlive(true).setReuseAddress(true))
			.withLoadBalancingPolicy(new RoundRobinPolicy())
			.withReconnectionPolicy(new ConstantReconnectionPolicy(500L))
			.withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.ONE))
			.build ();
	
	session = cluster.newSession();
	preparedStatements = new ConcurrentHashMap<StatementName, PreparedStatement> ();
	prepareStatementCreateLock = new Object();
}
 
开发者ID:att,项目名称:dmaap-framework,代码行数:27,代码来源:CassandraConfigDb.java

示例14: createRow

import com.datastax.driver.core.PreparedStatement; //导入依赖的package包/类
private String createRow(String key, String appid, String row) {
	if (StringUtils.isBlank(key) || StringUtils.isBlank(appid) || row == null || row.isEmpty()) {
		return null;
	}
	try {
		// if there isn't a document with the same id then create a new document
		// else replace the document with the same id with the new one
		PreparedStatement ps = getPreparedStatement("INSERT INTO " +
				CassandraUtils.getTableNameForAppid(appid) + " (id, json) VALUES (?, ?);");
		getClient().execute(ps.bind(key, row));
		logger.debug("Created id: " + key + " row: " + row);
	} catch (Exception e) {
		logger.error(null, e);
	}
	return key;
}
 
开发者ID:Erudika,项目名称:para-dao-cassandra,代码行数:17,代码来源:CassandraDAO.java

示例15: updateRow

import com.datastax.driver.core.PreparedStatement; //导入依赖的package包/类
private <P extends ParaObject> void updateRow(P so, String appid) {
	if (so == null || so.getId() == null || StringUtils.isBlank(appid)) {
		return;
	}
	try {
		String oldRow = readRow(so.getId(), appid);
		if (oldRow != null) {
			Map<String, Object> oldData = ParaObjectUtils.getJsonReader(Map.class).readValue(oldRow);
			Map<String, Object> newData = ParaObjectUtils.getAnnotatedFields(so, Locked.class);
			oldData.putAll(newData);
			PreparedStatement ps = getPreparedStatement("UPDATE " +
					CassandraUtils.getTableNameForAppid(appid) + " SET json = ? WHERE id = ?;");
			getClient().execute(ps.bind(ParaObjectUtils.getJsonWriterNoIdent().
					writeValueAsString(oldData), so.getId()));
			logger.debug("Updated id: " + so.getId());
		}
	} catch (Exception e) {
		logger.error(null, e);
	}
}
 
开发者ID:Erudika,项目名称:para-dao-cassandra,代码行数:21,代码来源:CassandraDAO.java


注:本文中的com.datastax.driver.core.PreparedStatement类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。