-
Notifications
You must be signed in to change notification settings - Fork 8
/
sql_connect.py
108 lines (84 loc) · 3.14 KB
/
sql_connect.py
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#!/usr/bin/python
import psycopg2
from config import config
def connect():
""" Connect to the PostgreSQL database server """
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
# execute a statement
print('PostgreSQL database version:')
cur.execute('SELECT version()')
# display the PostgreSQL database server version
db_version = cur.fetchone()
print(db_version)
cur.execute('SELECT * from api_data')
rows = cur.fetchall()
for row in rows:
print(row)
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
def api_ins(api_data):
""" Connect to the PostgreSQL database server and insert api data """
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database to insert values...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
# insert multiple rows of api data
cur.executemany(
"""INSERT INTO api_data (title,current_price,buy_now,country,url)
VALUES(%(title)s,%(current_price)s,%(buy_now)s,%(country)s,%(url)s)""",api_data
)
conn.commit()
print('Successfully data inserted in to the table...\n')
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')
def sold_ins(sold_data):
""" Connect to the PostgreSQL database server and insert api data """
conn = None
try:
# read connection parameters
params = config()
# connect to the PostgreSQL server
print('Connecting to the PostgreSQL database to insert values...')
conn = psycopg2.connect(**params)
# create a cursor
cur = conn.cursor()
# insert multiple rows of api data
cur.executemany(
"""INSERT INTO sold_data (description, bid)
VALUES(%(description)s,%(bid)s)""",sold_data
)
conn.commit()
print('Successfully data inserted in to the table...\n')
# close the communication with the PostgreSQL
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
print('Database connection closed.')