mirror of
https://github.com/michivonah/python.git
synced 2025-12-22 20:46:29 +01:00
create db functions script for postgresql
This commit is contained in:
parent
cfce308a2e
commit
2fed3030ac
1 changed files with 40 additions and 0 deletions
40
sql/dbfunctions.py
Normal file
40
sql/dbfunctions.py
Normal file
|
|
@ -0,0 +1,40 @@
|
||||||
|
# DB Functions for PostgreSQL
|
||||||
|
# install pip3 install psycopg2
|
||||||
|
from dotenv import load_dotenv
|
||||||
|
import os
|
||||||
|
import psycopg2
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
# load enviromental variables
|
||||||
|
load_dotenv()
|
||||||
|
|
||||||
|
# Create a connection to database
|
||||||
|
def connectDatabase():
|
||||||
|
conn = psycopg2.connect(
|
||||||
|
host=os.getenv('DBHOST'),
|
||||||
|
database=os.getenv('DBNAME'),
|
||||||
|
user=os.getenv('DBUSER'),
|
||||||
|
password=os.getenv('DBPASSWORD'),
|
||||||
|
port=os.getenv('DBPORT'),)
|
||||||
|
conn.autocommit = True
|
||||||
|
cursor = conn.cursor()
|
||||||
|
return cursor
|
||||||
|
|
||||||
|
def executeQuery(query):
|
||||||
|
conn = connectDatabase()
|
||||||
|
conn.execute(query)
|
||||||
|
result = conn.fetchall()
|
||||||
|
return result
|
||||||
|
|
||||||
|
def executeWithoutFetch(query):
|
||||||
|
conn = connectDatabase()
|
||||||
|
conn.execute(query)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def loadTable(query):
|
||||||
|
conn = connectDatabase()
|
||||||
|
conn.execute(query)
|
||||||
|
result = conn.fetchall()
|
||||||
|
colnames = [desc[0] for desc in conn.description]
|
||||||
|
df = pd.DataFrame(result, columns=colnames)
|
||||||
|
return df
|
||||||
Loading…
Add table
Add a link
Reference in a new issue