欢迎投稿

今日深度:

cassandra数据库使用(五)--使用python进行数据操作,cassandrapython

cassandra数据库使用(五)--使用python进行数据操作,cassandrapython


一、简介
这一节,将介绍使用python对cassandra进行数据操作,包括会话的连接和数据的增删改查。
二、使用
这里仍然直接上代码,解释请查看代码注释。

#! /usr/bin/env python
# -*- coding:utf8 -*-
from cassandra.cluster import Cluster
from cassandra.policies import RoundRobinPolicy


def main():
    # 获取集群
    cluster = Cluster(contact_points=['192.168.0.1'],
                      port=9042,
                      load_balancing_policy=RoundRobinPolicy())
    # 获取指定keyspace的会话连接
    session = cluster.connect(keyspace='key_space_1')

    # 查询所有
    sql = 'select * from stu'
    rs = session.execute(sql)
    print(rs.current_rows)

    # 主键id查询
    sql = 'select * from stu where stu_id=%s'
    # rs = session.execute(sql, [23]) #另一种写法,其它类似
    rs = session.execute(sql, (23,))
    print(rs.current_rows)

    # 条件查询
    sql = 'select * from stu where stu_name=%s '
    rs = session.execute(sql, ('apple3',))
    print(rs.current_rows)

    # 保存或更新,和update类似
    sql = 'insert into stu(stu_id,stu_name) values(%s, %s)'
    session.execute(sql, (11, 'apple11_1'))

    # 保存或更新,和insert类似
    sql='update stu set stu_name=%s where stu_id=%s'
    session.execute(sql, ('apple11_2', 13))

    # 删除
    sql = 'delete from stu where stu_id=%s '
    session.execute(sql, (11,))

    # 关键连接
    session.shutdown()

if __name__ == '__main__':
    main()

www.htsjk.Com true http://www.htsjk.com/cassandra/26424.html NewsArticle cassandra数据库使用(五)--使用python进行数据操作,cassandrapython 一、简介 这一节,将介绍使用python对cassandra进行数据操作,包括会话的连接和数据的增删改查。 二、使用 这里仍然直接上...
相关文章
    暂无相关文章
评论暂时关闭