Erstellen Sie Tabellen mit Psycopg2 Python
commands = [
"""
CREATE TABLE IF NOT EXISTS a_student (
student_id VARCHAR PRIMARY KEY,
gender VARCHAR,
ageGroup VARCHAR,
year FLOAT,
area VARCHAR
)
""",
"""
CREATE TABLE IF NOT EXISTS b_grade (
grade_student_id VARCHAR PRIMARY KEY,
gpa_all FLOAT,
gpa13s FLOAT,
cs65 FLOAT,
FOREIGN KEY(grade_student_id) REFERENCES a_student (student_id) ON UPDATE CASCADE ON DELETE CASCADE
)
"""
]
conn = pg.connect(host=host,port = port, database=database,user=user,password=password)
try:
cur = conn.cursor()
# create table one by one
for command in tqdm(commands):
cur.execute(command)
temp_tables = []
cur.execute("""SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'""")
for table in cur.fetchall():
temp_tables.append(table[0])
print("Current tables in the database {} are: {}. ".format(database,','.join(map(str,temp_tables))))
# close communication with the PostgreSQL database server
cur.close()
# commit the changes
conn.commit()
except (Exception, pg.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()
Rafael Oliveira