TDengine/docs/examples/python/stmt_ws.py

71 lines
1.9 KiB
Python
Raw Normal View History

2024-08-02 18:51:12 +00:00
from datetime import datetime
import random
import taosws
2024-08-02 18:51:12 +00:00
numOfSubTable = 10
2024-08-02 18:51:12 +00:00
numOfRow = 10
2024-08-02 18:51:12 +00:00
conn = None
stmt = None
2024-08-12 06:13:31 +00:00
host="localhost"
port=6041
2024-08-02 18:51:12 +00:00
try:
conn = taosws.connect(user="root",
password="taosdata",
2024-08-15 05:06:47 +00:00
host=host,
port=port)
2024-08-02 18:51:12 +00:00
conn.execute("CREATE DATABASE IF NOT EXISTS power")
conn.execute("USE power")
conn.execute(
"CREATE TABLE IF NOT EXISTS `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
)
2024-08-02 18:51:12 +00:00
# ANCHOR: stmt
sql = "INSERT INTO ? USING meters (groupid, location) TAGS(?,?) VALUES (?,?,?,?)"
stmt = conn.statement()
stmt.prepare(sql)
2024-08-02 18:51:12 +00:00
for i in range(numOfSubTable):
tbname = f"d_bind_{i}"
2024-08-02 18:51:12 +00:00
tags = [
taosws.int_to_tag(i),
taosws.varchar_to_tag(f"location_{i}"),
]
stmt.set_tbname_tags(tbname, tags)
current = int(datetime.now().timestamp() * 1000)
timestamps = []
currents = []
voltages = []
phases = []
2024-08-03 13:58:17 +00:00
for j in range (numOfRow):
2024-08-02 18:51:12 +00:00
timestamps.append(current + i)
currents.append(random.random() * 30)
2024-08-05 04:08:17 +00:00
voltages.append(random.randint(100, 300))
2024-08-02 18:51:12 +00:00
phases.append(random.random())
2024-08-02 18:51:12 +00:00
stmt.bind_param(
[
taosws.millis_timestamps_to_column(timestamps),
taosws.floats_to_column(currents),
taosws.ints_to_column(voltages),
taosws.floats_to_column(phases),
]
)
2024-08-02 18:51:12 +00:00
stmt.add_batch()
2024-08-05 04:08:17 +00:00
stmt.execute()
2024-08-12 06:13:31 +00:00
print(f"Successfully inserted to power.meters.")
2024-08-03 13:58:17 +00:00
2024-08-02 18:51:12 +00:00
except Exception as err:
2024-08-14 08:25:22 +00:00
print(f"Failed to insert to table meters using stmt, ErrMessage:{err}")
2024-09-26 03:13:32 +00:00
raise err
2024-08-02 18:51:12 +00:00
finally:
if stmt:
stmt.close()
2024-08-03 13:58:17 +00:00
if conn:
2024-08-02 18:51:12 +00:00
conn.close()