read_example.py 2.4 KB
Newer Older
S
slguan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
"""
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
L
liuyq-617 已提交
25 26 27 28 29 30
    if len(sys.argv)>1:
        hostname=sys.argv[1]
        conn = taos.connect(host=hostname, user="root", password="taosdata", config="/etc/taos")
    else:
        conn = taos.connect(host="127.0.0.1", user="root", password="taosdata", config="/etc/taos")
   
S
slguan 已提交
31 32 33 34
    # Generate a cursor object to run SQL commands
    c1 = conn.cursor()
    # Create a database named db
    try:
L
liu0x54 已提交
35
        c1.execute('create database if not exists db ')
S
slguan 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
    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 
T
Tao Liu 已提交
56
    for i in range(10):
S
slguan 已提交
57
        try:
T
Tao Liu 已提交
58 59 60
           value = c1.execute("insert into t values ('%s', %d, %f, '%s')" % (start_time, random.randint(1,10), random.randint(1,10)/10.0, 'hello'))
           #if insert, value is the affected rows
           print(value)
S
slguan 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
        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()

T
Tao Liu 已提交
78 79 80 81 82
    for col in data:
        print(col)

    print('Another query method ')

S
slguan 已提交
83 84 85 86 87 88 89 90 91 92 93
    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()