Just giving credit where credit is due: these are my notes fromĀ A udemy course I am taking
PYTHON ACCESS
This is what we honestly wanted out of this class
import psycopg2 as pg2
# Set up the connection details
config = {
'user': 'dhimes',
'password': 'dhimes-password-1',
'host': '192.168.0.56',
'database': 'mydb',
}
# Connect to the database
try:
conn = pg2.connect(**config)
print('Connected to the database')
except pg2.Error as err:
print(f'Error connecting to the database: {err}')
exit(1)
# Execute a SELECT statement
try:
# The cursor is the active part of this: it's the part of the conn
# that actually does things
cursor = conn.cursor()
cursor.execute('SELECT * FROM mytable')
rows = cursor.fetchall()
for row in rows:
print(row)
except pg2.Error as err:
print(f'Error executing SELECT statement: {err}')
exit(1)
# Close the cursor and connection
cursor.close()
conn.close()
VIEWS
You have a query you are running a lot, a view lets you use this as a starting point. The VIEW is just a stored query.
CREATE VIEW view_name AS SELECT * FROM customer;
So I can now do “SELECT * FROM view_name” obviously you’ll probably want a more complex call than the one above
To change it you would just do: CREATE OR REPLACE VIEW find_jerks AS SELECT * FROM customer WHERE customer_description = ‘jerk’;
Remove view with DROP VIEW IF EXISTS find_jerks
Change name: ALTER VIEW find_jerks RENAME TO find_problem_customers;
IMPORT/EXPORT
This is a PGAdmin thing, not a SQL statment. It import/export data from .csv into a table