-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUCIRP TC Postgresql script
74 lines (60 loc) · 2.14 KB
/
UCIRP TC Postgresql script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# UCIRP TC Postgresql script
# by Robert Woo
import psycopg2
from datetime import datetime as dt
import time
#Change to fit UCI Rocket's names
hostname = 'localhost'
database = 'postgres'
username = 'postgres'
pwd = 'postgres'
port_id = 5432
conn = None
cur = None
try:# to not crash program
#how the code connects to the database, how it opens database connection, allows to perform database transactions
#check out what the with clause does
conn = psycopg2.connect(
host = hostname,
dbname = database,
user = username,
password = pwd,
port = port_id)
tc_all = "1.1, 2.1, 3.1, 4.1" #test values for code
tc_all = tc_all.split(',')
print(tc_all)
tc1 = float(tc_all[0])
tc2 = float(tc_all[1])
tc3 = float(tc_all[2])
tc4 = float(tc_all[3])
print(tc4)
cur = conn.cursor() #opens a cursor, stores values from sql operations
cur.execute('DROP TABLE IF EXISTS tc_only')#drops table data when code runs
conn.commit()
#syntax of code of sql is exactly same in python
create_script = ''' CREATE TABLE IF NOT EXISTS tc_only (
TC1 float,
TC2 float,
TC3 float,
TC4 float,
Time TIMESTAMP NOT NULL)'''
cur.execute(create_script) #executes script
insert_script = 'INSERT INTO tc_only (TC1, TC2, TC3, TC4, Time) VALUES (%s, %s, %s, %s, %s)' #insert command,%s are placeholders
for i in range(100):
time.sleep(0.1)
tc1 = tc1 + 1
tc2 = tc2 + 10
tc3 = tc3 + 0.1
tc4 = tc4 + 0.01
insert_values = (tc1, tc2, tc3, tc4, dt.now())
cur.execute(insert_script, insert_values)
conn.commit()#save transactions into database
except Exception as error:
print(error)
finally:
#need to close connection before closing python program
#If statements allow for the close of database and cursor if connection works
if cur is not None:
cur.close() # needs to be closed after program is over
if conn is not None:
conn.close() #closes database