您的位置:首页 > 编程语言 > Python开发

python访问TimeScaleDB

2020-02-02 17:12 106 查看

封装了一个通过python访问TimeScaleDB的类,代码如下:

# 导入依赖包
# !/usr/bin/python3
import time
import datetime
import psycopg2

class TimeScaleDBVisiter():
def __init__(self):

self.beginTime = datetime.datetime.now()
#microsecond = self.beginTime + datetime.timedelta(microseconds=1000100)
#-- Do not forget to create timescaledb extension
#CREATE EXTENSION timescaledb;

# 创建表
# cur.execute("CREATE TABLE student(id integer,name varchar,sex varchar);")
strCreateTable = "CREATE TABLE conditions (   \
time        TIMESTAMPTZ       NOT NULL, \
location    TEXT              NOT NULL, \
temperature DOUBLE PRECISION  NULL, \
humidity    DOUBLE PRECISION  NULL \
);"
strCreateTable = "CREATE TABLE AllPulses (   \
id    integer NOT NULL, \
rd    integer NOT NULL, \
paw    integer NOT NULL, \
soa   TIMESTAMPTZ NOT NULL, \
inp   integer NOT NULL, \
moa   integer NOT NULL, \
pan    integer NOT NULL \
);"

#-- Then we convert it into a hypertable that is partitioned by time
#SELECT create_hypertable('conditions', 'time');
def Init(self):
# 创建连接对象
self.conn = psycopg2.connect(database="postgres", user="postgres", password="Pswiee2006*", host="localhost", port="5432")
self.cur = self.conn.cursor()  # 创建指针对象

def SaveInputs(self, dictInput):
# 插入数据
#cur.execute("INSERT INTO student(id,name,sex)VALUES(%s,%s,%s)", (1, 'Aspirin', 'M'))
#cur.execute("INSERT INTO student(id,name,sex)VALUES(%s,%s,%s)", (2, 'Taxol', 'F'))
#self.cur.execute("INSERT INTO conditions(time, location, temperature, humidity) VALUES (NOW(), 'office', 70.0, 50.0);")
tmpTime = self.beginTime + datetime.timedelta(microseconds=dictInput['soa'])
self.cur.execute("INSERT INTO AllPulses(id, rd, paw, soa, inp, moa, pan) VALUES (%s, %s, %s, make_timestamptz(%s,%s,%s,%s,%s,%s,'Asia/Shanghai'), %s, %s, %s);",
(dictInput['id'], dictInput['rd'],dictInput['paw'], tmpTime.year, tmpTime.month, tmpTime.day, tmpTime.hour, tmpTime.minute, tmpTime.second + tmpTime.microsecond*0.000001,
dictInput['inp'], dictInput['moa'], dictInput['pan']))
#self.cur.execute("INSERT INTO AllPulses(id, rf, pw, toa, inpulse, doa, pa) VALUES (1, 1000, 20, make_timestamptz(2019,1,2,13,50,1.5684,'Asia/Shanghai'),1, 345, 23);")
self.conn.commit()

def GetDatas(self):

# 获取结果
self.cur.execute('SELECT * FROM conditions ORDER BY time DESC LIMIT 100;')
results = self.cur.fetchall()
print(results)

def Close(self):
# 关闭连接
self.conn.commit()
self.cur.close()
self.conn.close()

dictPulse = {}
dictPulse['rd'] = 1000000
dictPulse['paw'] = 20
dictPulse['inp'] = 1
dictPulse['moa'] = 35000
dictPulse['pan'] = 14
dbVisitor = TimeScaleDBVisiter()
for i in range(100000):
dictPulse['id'] = i + 1
dictPulse['soa'] = i * 1000
dbVisitor.InsertPulse(dictPulse)
if i % 1000 == 0:
print("已插入%d条数据" % (i,))
  • 点赞 1
  • 收藏
  • 分享
  • 文章举报
常思大妹子 发布了11 篇原创文章 · 获赞 7 · 访问量 215 私信 关注
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: