75 lines
1.7 KiB
Python
75 lines
1.7 KiB
Python
#!/usr/bin/python
|
|
import psycopg2
|
|
from config import config
|
|
|
|
|
|
def insert_row(table_name, name):
|
|
sql = f"INSERT INTO {table_name}(id, name) VALUES(%s, %s) RETURNING id"
|
|
id = None
|
|
try:
|
|
database_config = config()
|
|
with psycopg2.connect(**database_config) as conn:
|
|
with conn.cursor() as cur:
|
|
cur.execute(sql, (1, name))
|
|
rows = cur.fetchone()
|
|
if rows:
|
|
id = rows[0]
|
|
|
|
conn.commit()
|
|
except (Exception, psycopg2.DatabaseError) as error:
|
|
print(error)
|
|
finally:
|
|
return id
|
|
|
|
def create_table(table_name):
|
|
conn = None
|
|
try:
|
|
params = config()
|
|
conn = psycopg2.connect(**params)
|
|
cur = conn.cursor()
|
|
|
|
cur.execute(f"CREATE TABLE {table_name}(id INTEGER PRIMARY KEY, name TEXT);")
|
|
|
|
cur.close()
|
|
conn.commit()
|
|
except (Exception, psycopg2.DatabaseError) as error:
|
|
print(error)
|
|
finally:
|
|
if conn is not None:
|
|
conn.close()
|
|
|
|
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)
|
|
|
|
# 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.')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
# create_table("mytable")
|
|
print(insert_row('mytable', 'ted')) |