first test
This commit is contained in:
commit
8a8fed9c7d
BIN
__pycache__/config.cpython-312.pyc
Normal file
BIN
__pycache__/config.cpython-312.pyc
Normal file
Binary file not shown.
21
config.py
Normal file
21
config.py
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
#!/usr/bin/python
|
||||||
|
from configparser import ConfigParser
|
||||||
|
|
||||||
|
|
||||||
|
def config(filename='database.ini', section='postgresql'):
|
||||||
|
# create a parser
|
||||||
|
parser = ConfigParser()
|
||||||
|
# read config file
|
||||||
|
parser.read(filename)
|
||||||
|
|
||||||
|
# get section, default to postgresql
|
||||||
|
db = {}
|
||||||
|
if parser.has_section(section):
|
||||||
|
params = parser.items(section)
|
||||||
|
for param in params:
|
||||||
|
db[param[0]] = param[1]
|
||||||
|
else:
|
||||||
|
raise Exception('Section {0} not found in the {1} file'.format(section, filename))
|
||||||
|
|
||||||
|
return db
|
||||||
|
|
||||||
6
database.ini
Normal file
6
database.ini
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
[postgresql]
|
||||||
|
host=192.168.1.67
|
||||||
|
database=test
|
||||||
|
user=test
|
||||||
|
password=test
|
||||||
|
port=5432
|
||||||
38
main.py
Normal file
38
main.py
Normal file
@ -0,0 +1,38 @@
|
|||||||
|
#!/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)
|
||||||
|
|
||||||
|
# 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__':
|
||||||
|
connect()
|
||||||
Loading…
x
Reference in New Issue
Block a user