来源:python中国网 时间:2020-03-14

  clickhouse是一款牛逼的数据库,是战斗民族俄罗斯人发明的,而且目前没有完整的中文版文档,和普通数据库不同之处在于他是列式存储!python操作clickhouse也有响应的接口。安装用pip命令即可。

	  pip installclickhouse_driver

  纯客户端示例:

# -*- coding: utf-8 -*-
from clickhouse_driver import Client

client = Client('localhost')
client.execute('SHOW TABLES')
client.execute('DROP TABLE IF EXISTS test')
client.execute('CREATE TABLE test (x Int32) ENGINE = Memory')
client.execute(
         'INSERT INTO test (x) VALUES',
         [{'x': 100}]
     )
client.execute('INSERT INTO test (x) VALUES', [[200]])
client.execute(
         'INSERT INTO test (x) '
         'SELECT * FROM system.numbers LIMIT %(limit)s',
         {'limit': 3}
     )
client.execute('SELECT sum(x) FROM test')


  使用数据库API:

 from clickhouse_driver import connect

 
 conn = connect('clickhouse://localhost')
 cursor = conn.cursor()
 cursor.execute('SHOW TABLES')
 cursor.fetchall()
 cursor.execute('DROP TABLE IF EXISTS test')
 cursor.fetchall()
 cursor.execute('CREATE TABLE test (x Int32) ENGINE = Memory')
 cursor.fetchall()
 cursor.executemany(
        'INSERT INTO test (x) VALUES',
        [{'x': 100}]
    )
 cursor.rowcount
 cursor.executemany('INSERT INTO test (x) VALUES', [[200]])
 cursor.rowcount
 cursor.execute(
        'INSERT INTO test (x) '
        'SELECT * FROM system.numbers LIMIT %(limit)s',
        {'limit': 3}
    )
 cursor.rowcount
 cursor.execute('SELECT sum(x) FROM test')
 cursor.fetchall()



  参考文档:

  https://pypi.org/project/clickhouse-driver/

  https://github.com/mymarilyn/clickhouse-driver

疑难杂症

Tips:不要怕、多坚持、多动手、付出必有回报。