• 应用驱动安装请参考。
    • 已安装python 2.7 or >= 3.4
    • 已安装pip 或 pip3

    Linux

    用户可以在源代码的src/connector/python(或者tar.gz的/connector/python)文件夹下找到python2和python3的connector安装包。用户可以通过pip命令安装:

    pip3 install src/connector/python/linux/python3/

    Windows

    1. cd C:\TDengine\connector\python\windows
    2. python -m pip install python3\
    • 如果机器上没有pip命令,用户可将src/connector/python/python3或src/connector/python/python2下的taos文件夹拷贝到应用程序的目录使用。 对于windows 客户端,安装TDengine windows 客户端后,将C:\TDengine\driver\taos.dll拷贝到C:\windows\system32目录下即可。

    代码示例

    • 导入TDengine客户端模块
    1. import taos
    • 获取连接并获取游标对象
    • host 是TDengine 服务端所有IP, config 为客户端配置文件所在目录

    • 写入数据

    1. import datetime
    2. c1.execute('create database db')
    3. c1.execute('use db')
    4. # 建表
    5. c1.execute('create table tb (ts timestamp, temperature int, humidity float)')
    6. # 插入数据
    7. affected_rows = c1.execute('insert into tb values (\'%s\', 0, 0.0)' %start_time)
    8. # 批量插入数据
    9. time_interval = datetime.timedelta(seconds=60)
    10. sqlcmd = ['insert into tb values']
    11. for irow in range(1,11):
    12. start_time += time_interval
    13. sqlcmd.append('(\'%s\', %d, %f)' %(start_time, irow, irow*1.2))
    14. affected_rows = c1.execute(' '.join(sqlcmd))
    • 查询数据
    1. c1.execute('select * from tb')
    2. # 拉取查询结果
    3. data = c1.fetchall()
    4. # 返回的结果是一个列表,每一行构成列表的一个元素
    5. numOfCols = len(c1.description)
    6. print("Row%d: ts=%s, temperature=%d, humidity=%f" %(irow, data[irow][0], data[irow][1],data[irow][2]))
    7. # 直接使用cursor 循环拉取查询结果
    8. c1.execute('select * from tb')
    9. for data in c1:
    10. print("ts=%s, temperature=%d, humidity=%f" %(data[0], data[1],data[2]))
    • 创建订阅
    • 消费订阅的数据
    1. data = sub.consume()
    2. for d in data:
    3. print(d)
    • 取消订阅
    1. sub.close()
    • 关闭连接

    帮助信息

    用户可通过python的帮助信息直接查看模块的使用信息,或者参考tests/examples/python中的示例程序。以下为部分常用类和方法:

    • 参考python中help(taos.TDengineConnection)。 这个类对应客户端和TDengine建立的一个连接。在客户端多线程的场景下,推荐每个线程申请一个独立的连接实例,而不建议多线程共享一个连接。

    • TDengineCursor

      参考python中help(taos.TDengineCursor)。 这个类对应客户端进行的写入、查询操作。在客户端多线程的场景下,这个游标实例必须保持线程独享,不能夸线程共享使用,否则会导致返回结果出现错误。

    • connect 方法

    在tests/examples/python中,我们提供了一个示例Python程序read_example.py,可以参考这个程序来设计用户自己的写入、查询程序。在安装了对应的客户端后,通过import taos引入taos类。主要步骤如下

    • 通过taos.connect获取TDengineConnection对象,这个对象可以一个程序只申请一个,在多线程中共享。
    • 通过TDengineConnection对象的 .cursor()方法获取一个新的游标对象,这个游标对象必须保证每个线程独享。
    • 通过游标对象的execute()方法,执行写入或查询的SQL语句
    • 如果执行的是写入语句,execute返回的是成功写入的行数信息affected rows