json_protocol_example.py 1.2 KB
Newer Older
D
dingbo 已提交
1 2 3 4 5
import json

import taos
from taos import SmlProtocol, SmlPrecision

6
lines = [{"metric": "meters.current", "timestamp": 1648432611249, "value": 10.3, "tags": {"location": "Beijing.Chaoyang", "groupid": 2}},
B
Bo Ding 已提交
7 8 9 10
         {"metric": "meters.voltage", "timestamp": 1648432611249, "value": 219,
             "tags": {"location": "Beijing.Haidian", "groupid": 1}},
         {"metric": "meters.current", "timestamp": 1648432611250, "value": 12.6,
             "tags": {"location": "Beijing.Chaoyang", "groupid": 2}},
11
         {"metric": "meters.voltage", "timestamp": 1648432611250, "value": 221, "tags": {"location": "Beijing.Haidian", "groupid": 1}}]
D
dingbo 已提交
12 13


D
dingbo 已提交
14 15
def get_connection():
    return taos.connect()
D
dingbo 已提交
16

D
dingbo 已提交
17 18

def create_database(conn):
B
Bo Ding 已提交
19 20
    conn.execute("CREATE DATABASE test")
    conn.execute("USE test")
D
dingbo 已提交
21 22


D
dingbo 已提交
23
def insert_lines(conn):
D
dingbo 已提交
24
    global lines
25 26
    lines = json.dumps(lines)
    # note: the first parameter must be a list with only one element.
B
Bo Ding 已提交
27 28
    affected_rows = conn.schemaless_insert(
        [lines], SmlProtocol.JSON_PROTOCOL, SmlPrecision.NOT_CONFIGURED)
29
    print(affected_rows)  # 4
D
dingbo 已提交
30 31 32


if __name__ == '__main__':
D
dingbo 已提交
33
    connection = get_connection()
34 35 36 37 38
    try:
        create_database(connection)
        insert_lines(connection)
    finally:
        connection.close()