· 4 years ago · Mar 29, 2021, 10:30 PM
1# Basic Execution
2conn = psycopg2.connect("host=127.0.0.1 dbname=studentdb user=student password=student")
3cur = conn.cursor()
4conn.set_session(autocommit=True)
5cur.execute("CREATE TABLE test (col1 int, col2 int, col3 int);")
6cur.execute("select * from test")
7cur.close()
8conn.close()
9
10# Create Table
11try:
12 cur.execute("CREATE TABLE IF NOT EXISTS music_library (album_name varchar, artist_name varchar, year int);")
13except psycopg2.Error as e:
14 print("Error: Issue creating table")
15 print (e)
16
17# Insert Rows
18try:
19 cur.execute("INSERT INTO music_library (album_name, artist_name, year) \
20 VALUES (%s, %s, %s)", \
21 ("Let It Be", "The Beatles", 1970))
22except psycopg2.Error as e:
23 print("Error: Inserting Rows")
24 print (e)
25
26try:
27 cur.execute("INSERT INTO music_library (album_name, artist_name, year) \
28 VALUES (%s, %s, %s)", \
29 ("Rubber Soul", "The Beatles", 1965))
30except psycopg2.Error as e:
31 print("Error: Inserting Rows")
32 print (e)
33
34# Drop Tables
35try:
36 cur.execute("DROP table music_library")
37except psycopg2.Error as e:
38 print("Error: Dropping table")
39 print (e)