Skip to content

Instantly share code, notes, and snippets.

@omonimus1
Last active July 21, 2022 08:47
Show Gist options
  • Save omonimus1/9e2ec97c943518cd52e7ba6eaa4b037a to your computer and use it in GitHub Desktop.
Save omonimus1/9e2ec97c943518cd52e7ba6eaa4b037a to your computer and use it in GitHub Desktop.
import psycopg2 # python3 -m pip install psycopg2-binary
# Update connection string information
host = ""
dbname = ""
user = ""
password = “”
sslmode = "require"
# Construct connection string
conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password, sslmode)
conn = psycopg2.connect(conn_string)
print("Connection established")
cursor = conn.cursor()
# Drop previous table of same name if one exists
cursor.execute("DROP TABLE IF EXISTS inventory;")
print("Finished dropping table (if existed)")
# Create a table
cursor.execute("CREATE TABLE inventory (id serial PRIMARY KEY, name VARCHAR(50), quantity INTEGER);")
print("Finished creating table")
# Insert some data into the table
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("iphone 14 Pro Max", 99))
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("Macbook Pro", 90))
cursor.execute("INSERT INTO inventory (name, quantity) VALUES (%s, %s);", ("Microsoft surface", 99))
print("Inserted 3 rows of data")
# Clean up
conn.commit()
cursor.close()
conn.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment