Source Code Snippets of "Create_Table.py"

Mike Dinder

The entire contents of the "Create_Table.py" file as code examples with syntax highlighting

Auto Generated Using Generate_HTML.py script to auto format each of these pages in a standardized template.

On smaller viewports/windows, please scroll or use your touch/finger to scroll left to right to view all the code displayed.

Create_Table Python Home
                                        # Create a Database Table
import psycopg2

from Connect import connect
from psycopg2 import sql
from psycopg2.extensions import AsIs


def create_table(conn, table_name='', columns=None) -> None:
    """
    Insert a new User into the User table and return the User ID.

    :param conn: Database Connection
    :param table_name: Database Table Name
    :param columns: List, Specifies the columns to write
    :returns: Nothing - Prints Status as Prompt Dialogue
    :rtype: None
    """
    cursor = conn.cursor()
    columns_sql = ', '.join(['%s'] * len(columns))
    query = f'CREATE TABLE IF NOT EXISTS {{}} ({columns_sql});'

    try:
        cursor.execute(
            sql.SQL(query).format(
                sql.Identifier(table_name)
            ),
            columns
        )
    except (Exception, psycopg2.DatabaseError) as e:
        print(f'Error Creating Table: {e}')
        conn.rollback()
    else:
        conn.commit()
        executed_query_bytes = cursor.query
        executed_query_str = executed_query_bytes.decode('utf-8')

        print(f'Executed Query: {executed_query_str}')
        print('Table Created Successfully.')
    finally:
        # Close the Cursor and Connection
        if cursor:
            cursor.close()

        # if conn:
        #     conn.close()


if __name__ == '__main__':
    conn = connect()

    if conn:
        create_table(conn, 'users', [
            AsIs('id SERIAL PRIMARY KEY'),
            AsIs('first_name VARCHAR(100)'),
            AsIs('last_name VARCHAR(100)'),
            AsIs('email VARCHAR(200)'),
            AsIs('UNIQUE(email)')
        ])

        conn.close()


                                        

Runs the entire script above. Open your Console Window in Inspect Code to view the output of the script above.

A prompt popup will ask you for various input() commands.

Python in Your Browser

Client-side execution via Pyodide · No server · Full stdlib · numpy, pandas, matplotlib available via micropip

Mobile users will want to use this method. Copy snippets or the entire script from above. You may also copy this script exactly as it is shown and you can run it on your own machine using the Command-Line Interface (CLI).

Loading Pyodide...
>>>
Enter run Shift+Enter new line ↑↓ history