Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

create tables with 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()
Comment

PREVIOUS NEXT
Code Example
Python :: Setting spacing between ticks in matplotlib 
Python :: access myultiple dict values with list pythojn 
Python :: python if string contains char 
Python :: how to create a virtual environment in python 
Python :: csv file sort python 
Python :: transpose matrix in python without numpy 
Python :: pandas read_excel 
Python :: Using a list with index and column names to Convert List to Dataframe 
Python :: add python to path 
Python :: django run management command from code 
Python :: python start process in background and get pid 
Python :: convert nan to string pandas 
Python :: How to install packages offline? Ask Question 
Python :: python autoclicker 
Python :: data where values in column starts with particular value 
Python :: how to code a yes or no question in python v3.8 
Python :: convert pandas dataframe to numpy dataframe 
Python :: python list join array string space 
Python :: browser = webdriver.firefox() error 
Python :: discord.py get id of sent message 
Python :: python get last element of array 
Python :: hugging face change directory model 
Python :: how to use for loop to take n number of input in python 
Python :: conda enviroment python version 
Python :: python filter() 
Python :: enumerate items python 
Python :: skimage local threshold 
Python :: check if variable is empty python 
Python :: python check variable size in memory 
Python :: for if else one line python 
ADD CONTENT
Topic
Content
Source link
Name
1+6 =