Cassandra教程
作者: 飘雪无垠
CURD操作

示例表:

//测试库
CREATE KEYSPACE myKeyspace WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};
//测试表
CREATE TABLE user (
    country text ,
    uid bigint,
    name text,
    age int,
    PRIMARY KEY(country,uid)
) WITH comment='user table';

插入数据:

        PreparedStatement prepareStatement = session.prepare("insert into  myKeyspace.user (country,uid,name,age) values (?,?,?,?)");
        BoundStatement bindStatement = new BoundStatement(prepareStatement).bind("CN", 1l, "zhangSan", 25);
        session.execute(bindStatement);

批量插入数据:

        PreparedStatement prepareStatement = session.prepare("insert into  myKeyspace.user (country,uid,name,age) values (?,?,?,?)");

        BoundStatement bindStatement1 = new BoundStatement(prepareStatement).bind("CN", 1l, "zhangSan", 25);
        BoundStatement bindStatement2 = new BoundStatement(prepareStatement).bind("CN", 2l, "liSi", 26);
        BoundStatement bindStatement3 = new BoundStatement(prepareStatement).bind("USA", 3l, "sam", 27);

        BatchStatement batchStatement = new BatchStatement();
        batchStatement.add(bindStatement1);
        batchStatement.add(bindStatement2);
        batchStatement.add(bindStatement3);

        session.execute(batchStatement);

查看单条数据:

        PreparedStatement prepareStatement = session.prepare("select * from  myKeyspace.user where country=? and uid=?");
        BoundStatement bindStatement = new BoundStatement(prepareStatement).bind("CN", 1l);
        ResultSet rs = session.execute(bindStatement);
        Row row = rs.one();
        System.out.println(row.getString("name")+","+row.getInt("age"));

查看所有数据:

        PreparedStatement prepareStatement = session.prepare("select * from  myKeyspace.user where country=?");
        BoundStatement bindStatement = new BoundStatement(prepareStatement).bind("CN");
        ResultSet rs = session.execute(bindStatement);
        List<Row> rowList = rs.all();
        rowList.forEach(row -> {
            System.out.println(row.getString("name") + "," + row.getInt("age"));
        });

更新数据:

        PreparedStatement prepareStatement = session.prepare("update  myKeyspace.user set age=30 where country=? and uid=?");
        BoundStatement bindStatement = new BoundStatement(prepareStatement).bind("CN", 1l);
        session.execute(bindStatement);

删除数据:

        PreparedStatement prepareStatement = session.prepare("delete from  myKeyspace.user  where country=? and uid=?");
        BoundStatement bindStatement = new BoundStatement(prepareStatement).bind("CN", 1l);
        session.execute(bindStatement);

清空所有数据:

        PreparedStatement prepareStatement = session.prepare("truncate  myKeyspace.user");
        BoundStatement bindStatement = new BoundStatement(prepareStatement);
        session.execute(bindStatement);


标签: boundstatement、preparestatement、bindstatement、mykeyspace、country
一个创业中的苦逼程序员
  • 回复
隐藏