add python example

This commit is contained in:
menshibin 2024-08-03 21:58:17 +08:00 committed by gccgdb1234
parent 2f20970190
commit 04f9a611c0
17 changed files with 121 additions and 223 deletions

View File

@ -3,15 +3,18 @@ import taos
def create_connection():
# all parameters are optional.
conn = None
host = "localhost"
port = 6030
try:
conn = taos.connect(
user="root",
password="taosdata",
host="localhost",
port=6030,
host=host,
port=port,
)
print(f"Connected to {host}:{port} successfully.");
except Exception as err:
print(err)
print(f"Failed to connect to {host}:{port} ; Err:{err}")
finally:
if conn:
conn.close()

View File

@ -3,16 +3,16 @@ import taosrest
def create_connection():
conn = None
url="http://localhost:6041"
try:
conn = taosrest.connect(url="http://localhost:6041",
conn = taosrest.connect(url=url,
user="root",
password="taosdata",
timeout=30)
print("Connection established")
print(f"Connected to {url} successfully.");
except Exception as err:
print(err)
print(f"Failed to connect to {url} ; Err:{err}")
finally:
if conn:
conn.close()

View File

@ -3,18 +3,20 @@ import taosws
def create_connection():
conn = None
host = "localhost"
port = 6041
try:
conn = taosws.connect(
user="root",
password="taosdata",
host="localhost",
port=6041,
host=host,
port=port,
)
print(f"Connected to {host}:{port} successfully.");
except Exception as err:
print(err)
print(f"Failed to connect to {host}:{port} ; Err:{err}")
return conn
# ANCHOR_END: connect
def create_db_table(conn):
@ -22,13 +24,10 @@ def create_db_table(conn):
try:
conn.execute("CREATE DATABASE IF NOT EXISTS power")
conn.execute("USE power")
conn.execute(
"CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
conn.execute("CREATE STABLE IF NOT EXISTS meters (ts TIMESTAMP, current FLOAT, voltage INT, phase FLOAT) TAGS (groupId INT, location BINARY(24))")
conn.execute("CREATE TABLE IF NOT EXISTS `d0` USING `meters` (groupId, location) TAGS(0, 'Los Angles')")
except Exception as err:
print(f'Exception {err}')
# ANCHOR_END: create_db
def insert(conn):
@ -43,11 +42,9 @@ def insert(conn):
"""
try:
inserted = conn.execute(sql)
assert inserted == 4
assert inserted == 8
except Exception as err:
print(f'Exception {err}')
print(f'Exception111 {err}')
# ANCHOR_END: insert
def query(conn):
@ -55,14 +52,12 @@ def query(conn):
try:
result = conn.query("select * from meters")
num_of_fields = result.field_count
print(f"query field conunt is {num_of_fields}")
print(num_of_fields)
for row in result:
print(row)
except Exception as err:
print(f'query Exception {err}')
print(f'Exception {err}')
# ANCHOR_END: query
if __name__ == "__main__":

View File

@ -1,11 +1,13 @@
import taos
conn = None
host = "localhost"
port = 6030
try:
conn = taos.connect(host="localhost",
conn = taos.connect(host=host,
port=port,
user="root",
password="taosdata",
port=6030)
password="taosdata")
db = "power"
# create database
@ -27,7 +29,7 @@ try:
assert rowsAffected == 0
except Exception as err:
print(err)
print(f"Failed to create db and table, db addrr:{host}:{port} err:{err}")
finally:
if conn:
conn.close()

View File

@ -1,8 +1,9 @@
import taosrest
conn = None
url = "http://localhost:6041"
try:
conn = taosrest.connect(url="http://localhost:6041",
conn = taosrest.connect(url=url,
user="root",
password="taosdata",
timeout=30)
@ -22,7 +23,7 @@ try:
assert rowsAffected == 0
except Exception as err:
print(err)
print(f"Failed to create db and table, url:{url} err:{err}")
finally:
if conn:
conn.close()

View File

@ -1,76 +1,35 @@
import taosws
conn = None
host = "localhost"
port = 6041
try:
conn = taosws.connect(user="root",
password="taosdata",
host=host,
port=port)
db = "power"
def prepare():
conn = None
try:
conn = taosws.connect(user="root",
password="taosdata",
host="192.168.1.98",
port=6041)
# create database
conn.execute(f"drop database if exists {db}")
conn.execute(f"create database {db}")
rowsAffected = conn.execute(f"CREATE DATABASE IF NOT EXISTS {db}")
assert rowsAffected == 0
# change database.
rowsAffected = conn.execute(f"USE {db}")
assert rowsAffected == 0
# create super table
rowsAffected = conn.execute(
"CREATE TABLE IF NOT EXISTS `meters` (`ts` TIMESTAMP, `current` FLOAT, `voltage` INT, `phase` FLOAT) TAGS (`groupid` INT, `location` BINARY(16))"
)
assert rowsAffected == 0
# create table
rowsAffected = conn.execute("CREATE TABLE IF NOT EXISTS `d0` USING `meters` (groupid, location) TAGS(0, 'Los Angles')")
assert rowsAffected == 0
except Exception as err:
print(err)
print(f"Failed to create db and table, db addrr:{host}:{port} err:{err}")
finally:
if conn:
conn.close()
def schemaless_insert():
conn = None
lineDemo = [
"meters,groupid=2,location=California.SanFrancisco current=10.3000002f64,voltage=219i32,phase=0.31f64 1626006833639"
]
telnetDemo = ["metric_telnet 1707095283260 4 host=host0 interface=eth0"]
jsonDemo = [
'{"metric": "metric_json","timestamp": 1626846400,"value": 10.3, "tags": {"groupid": 2, "location": "California.SanFrancisco", "id": "d1001"}}'
]
try:
conn = taosws.connect(user="root",
password="taosdata",
host="192.168.1.98",
port=6041,
database=db)
conn.schemaless_insert(
lines=lineDemo,
protocol=taosws.PySchemalessProtocol.Line,
precision=taosws.PySchemalessPrecision.Millisecond,
ttl=1,
req_id=1,
)
conn.schemaless_insert(
lines=telnetDemo,
protocol=taosws.PySchemalessProtocol.Telnet,
precision=taosws.PySchemalessPrecision.Microsecond,
ttl=1,
req_id=2,
)
conn.schemaless_insert(
lines=jsonDemo,
protocol=taosws.PySchemalessProtocol.Json,
precision=taosws.PySchemalessPrecision.Millisecond,
ttl=1,
req_id=3,
)
except Exception as err:
print(err)
finally:
if conn:
conn.close()
if __name__ == '__main__':
prepare()
schemaless_insert()

View File

@ -20,7 +20,7 @@ try:
print(row)
except Exception as err:
print(err)
print(f"Failed to query data from power.meters, err:{err}")
finally:
if conn:
conn.close()

View File

@ -8,8 +8,8 @@ try:
password="taosdata",
timeout=30)
result = client.sql(f"SELECT ts, current, location FROM power.meters limit 100")
result = client.sql(f"SELECT ts, current, location FROM power.meters limit 100", 1)
print(result)
except Exception as err:
print(err)
print(f"Failed to query data from power.meters, err:{err}")

View File

@ -16,7 +16,7 @@ try:
print(row)
except Exception as err:
print(err)
print(f"Failed to query data from power.meters, err:{err}")
finally:
if conn:
conn.close()

View File

@ -7,19 +7,7 @@ try:
user="root",
password="taosdata")
sql = """
INSERT INTO
power.d1001 USING power.meters (groupid, location) TAGS(2, 'California.SanFrancisco')
VALUES (NOW + 1a, 10.30000, 219, 0.31000)
(NOW + 2a, 12.60000, 218, 0.33000) (NOW + 3a, 12.30000, 221, 0.31000)
power.d1002 USING power.meters (groupid, location) TAGS(3, 'California.SanFrancisco')
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
"""
affectedRows = conn.execute(sql, 1)
print(f"inserted into {affectedRows} rows to power.meters successfully.")
result = conn.query("SELECT ts, current, location FROM power.meters limit 100", 2)
print(result)
result = conn.query("SELECT ts, current, location FROM power.meters limit 100", 1)
# Get fields from result
fields = result.fields
for field in fields:
@ -31,7 +19,7 @@ try:
print(row)
except Exception as err:
print(err)
print(f"Failed to execute sql with reqId, err:{err}")
finally:
if conn:
conn.close()

View File

@ -12,4 +12,4 @@ try:
print(result)
except Exception as err:
print(err)
print(f"Failed to execute sql with reqId, err:{err}")

View File

@ -10,26 +10,13 @@ try:
port=6041,
)
sql = """
INSERT INTO
power.d1001 USING power.meters (groupid, location) TAGS(2, 'California.SanFrancisco')
VALUES (NOW + 1a, 10.30000, 219, 0.31000)
(NOW + 2a, 12.60000, 218, 0.33000) (NOW + 3a, 12.30000, 221, 0.31000)
power.d1002 USING power.meters (groupid, location) TAGS(3, 'California.SanFrancisco')
VALUES (NOW + 1a, 10.30000, 218, 0.25000)
"""
affectedRows = conn.execute_with_req_id(sql, req_id=1)
print(f"inserted into {affectedRows} rows to power.meters successfully.")
result = conn.query_with_req_id("SELECT ts, current, location FROM power.meters limit 100", req_id=2)
num_of_fields = result.field_count
print(num_of_fields)
result = conn.query_with_req_id("SELECT ts, current, location FROM power.meters limit 100", req_id=1)
for row in result:
print(row)
except Exception as err:
print(err)
print(f"Failed to execute sql with reqId, err:{err}")
finally:
if conn:
conn.close()

View File

@ -32,7 +32,7 @@ try:
jsonDemo, taos.SmlProtocol.JSON_PROTOCOL, taos.SmlPrecision.MILLI_SECONDS
)
except Exception as err:
print(err)
print(f"Failed to insert data with schemaless, err:{err}")
finally:
if conn:
conn.close()

View File

@ -1,28 +1,5 @@
import taosws
db = "power"
def prepare():
conn = None
try:
conn = taosws.connect(user="root",
password="taosdata",
host="taosdata",
port=6041)
# create database
conn.execute(f"drop database if exists {db}")
conn.execute(f"create database {db}")
except Exception as err:
print(err)
raise err
finally:
if conn:
conn.close()
def schemaless_insert():
conn = None
lineDemo = [
@ -36,46 +13,35 @@ def schemaless_insert():
]
try:
conn = taosws.connect(user="root",
password="taosdata",
host="192.168.1.98",
port=6041,
database=db)
host="localhost",
port=6041)
conn.execute("CREATE DATABASE IF NOT EXISTS power")
conn = conn.execute("USE power")
conn.schemaless_insert(
lines=lineDemo,
protocol=taosws.PySchemalessProtocol.Line,
precision=taosws.PySchemalessPrecision.Millisecond,
ttl=1,
req_id=1,
precision=taosws.PySchemalessPrecision.Millisecond
)
conn.schemaless_insert(
lines=telnetDemo,
protocol=taosws.PySchemalessProtocol.Telnet,
precision=taosws.PySchemalessPrecision.Microsecond,
ttl=1,
req_id=2,
precision=taosws.PySchemalessPrecision.Microsecond
)
conn.schemaless_insert(
lines=jsonDemo,
protocol=taosws.PySchemalessProtocol.Json,
precision=taosws.PySchemalessPrecision.Millisecond,
ttl=1,
req_id=3,
precision=taosws.PySchemalessPrecision.Millisecond
)
except Exception as err:
print(err)
raise err
print(f"Failed to insert data with schemaless, err:{err}")
finally:
if conn:
conn.close()
if __name__ == '__main__':
try:
prepare()
schemaless_insert()
except Exception as err:
print(err)

View File

@ -42,7 +42,7 @@ try:
for j in range (numOfRow):
timestamps.append(current + i)
currents.append(random.random() * 30)
voltages.append(random.randint(100, 300))
voltages.append(random.random(100, 300))
phases.append(random.random())
params = taos.new_bind_params(4)
@ -52,10 +52,11 @@ try:
params[3].float(phases)
stmt.bind_param_batch(params)
stmt.execute()
print(f"table {tbname} insert ok.")
affected = stmt.affected_rows()
print(f"table {tbname} insert {affected} rows.")
except Exception as err:
print(err)
print(f"Failed to insert to table meters using stmt, error: {err}")
finally:
if stmt:
stmt.close()

View File

@ -41,7 +41,7 @@ try:
for j in range (numOfRow):
timestamps.append(current + i)
currents.append(random.random() * 30)
voltages.append(random.randint(100, 300))
voltages.append(random.random(100, 300))
phases.append(random.random())
stmt.bind_param(
@ -55,10 +55,10 @@ try:
stmt.add_batch()
rows = stmt.execute()
print(f"table {tbname} insert ok.")
print(f"insert {rows} rows.")
except Exception as err:
print(err)
print(f"Failed to insert to table meters using stmt, error: {err}")
finally:
if stmt:
stmt.close()

View File

@ -1,6 +1,5 @@
import taos
def prepareMeta():
conn = None
try:
@ -47,11 +46,8 @@ def prepareMeta():
conn.close()
# ANCHOR: create_consumer
from taos.tmq import Consumer
def create_consumer():
try:
consumer = Consumer(