read_example.py 2.1 KB
Newer Older
H
hzcheng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
"""
This is the sample code for TDengine python2 client.
"""
import taos
import sys
import datetime
import random

def exitProgram(conn):
    conn.close()
    sys.exit()

if __name__ == '__main__':
    start_time = datetime.datetime(2019, 7, 1)
    time_interval = datetime.timedelta(seconds=60)

    # Connect to TDengine server.
    # 
    # parameters:
    # @host     : TDengine server IP address 
    # @user     : Username used to connect to TDengine server
    # @password : Password 
    # @database : Database to use when connecting to TDengine server
    # @config   : Configuration directory
    conn = taos.connect(host="127.0.0.1", user="root", password="taosdata", config="/etc/taos")

    # Generate a cursor object to run SQL commands
    c1 = conn.cursor()

    # Create a database named db
    try:
        c1.execute('create database db')
    except Exception as err:
        conn.close()
        raise(err)
        
    # use database
    try:
        c1.execute('use db')
    except Exception as err:
        conn.close()
        raise(err)


    # create table
    try:
        c1.execute('create table if not exists t (ts timestamp, a int, b float, c binary(20))')
    except Exception as err:
        conn.close()
        raise(err)

    # insert data 
    for i in range(10000):
        try:
           c1.execute("insert into t values ('%s', %d, %f, '%s')" % (start_time, random.randint(1,10), random.randint(1,10)/10.0, 'hello'))
        except Exception as err:
            conn.close()
            raise(err)
        start_time += time_interval

    # query data and return data in the form of list
    try:
        c1.execute('select * from db.t')
    except Exception as err:
        conn.close()
        raise(err)

    # Column names are in c1.description list
    cols = c1.description
    # Use fetchall to fetch data in a list
    data = c1.fetchall()

    try:
        c1.execute('select * from db.t')
    except Exception as err:
        conn.close()
        raise(err)

    # Use iterator to go through the retreived data
    for col in c1:
        print(col)

    conn.close()