Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

how to create table in a database in python

import mysql.connector

try:
    connection = mysql.connector.connect(host='localhost',
                                         database='Electronics',
                                         user='pynative',
                                         password='pynative@#29')

    mySql_Create_Table_Query = """CREATE TABLE Laptop ( 
                             Id int(11) NOT NULL,
                             Name varchar(250) NOT NULL,
                             Price float NOT NULL,
                             Purchase_date Date NOT NULL,
                             PRIMARY KEY (Id)) """

    cursor = connection.cursor()
    result = cursor.execute(mySql_Create_Table_Query)
    print("Laptop Table created successfully ")

except mysql.connector.Error as error:
    print("Failed to create table in MySQL: {}".format(error))
finally:
    if connection.is_connected():
        cursor.close()
        connection.close()
        print("MySQL connection is closed")
Comment

create database tables python

import sqlite3
from sqlite3 import Error


def create_connection(db_file):
    """ create a database connection to the SQLite database
        specified by db_file
    :param db_file: database file
    :return: Connection object or None
    """
    conn = None
    try:
        conn = sqlite3.connect(db_file)
        return conn
    except Error as e:
        print(e)

    return conn


def create_table(conn, create_table_sql):
    """ create a table from the create_table_sql statement
    :param conn: Connection object
    :param create_table_sql: a CREATE TABLE statement
    :return:
    """
    try:
        c = conn.cursor()
        c.execute(create_table_sql)
    except Error as e:
        print(e)


def main():
    database = r"C:sqlitedbpythonsqlite.db"

    sql_create_projects_table = """ CREATE TABLE IF NOT EXISTS projects (
                                        id integer PRIMARY KEY,
                                        name text NOT NULL,
                                        begin_date text,
                                        end_date text
                                    ); """

    sql_create_tasks_table = """CREATE TABLE IF NOT EXISTS tasks (
                                    id integer PRIMARY KEY,
                                    name text NOT NULL,
                                    priority integer,
                                    status_id integer NOT NULL,
                                    project_id integer NOT NULL,
                                    begin_date text NOT NULL,
                                    end_date text NOT NULL,
                                    FOREIGN KEY (project_id) REFERENCES projects (id)
                                );"""

    # create a database connection
    conn = create_connection(database)

    # create tables
    if conn is not None:
        # create projects table
        create_table(conn, sql_create_projects_table)

        # create tasks table
        create_table(conn, sql_create_tasks_table)
    else:
        print("Error! cannot create the database connection.")


if __name__ == '__main__':
    main()
Code language: Python (python)
Comment

PREVIOUS NEXT
Code Example
Python :: django give access to media folder 
Python :: pandas interpolate string 
Python :: How to build a Least Recently Used (LRU) cache, in Python? 
Python :: programmer tool 
Python :: how to add find the smallest int n in a list python 
Python :: python genap ganjil 
Python :: python serial COM3 
Python :: django table view sort filter 
Python :: remove days when subtracting time python 
Python :: python function 
Python :: django-storages delete folder 
Python :: numpy filter based on value 
Python :: change edit last line python 
Python :: python list sum 
Python :: bad request 400 heroku app 
Python :: install pytorch on nvidia jetson nx 
Python :: interface in python 
Python :: python reading into a text file and diplaying items in a user friendly manner 
Python :: sqlalchemy one to one foreign key 
Python :: python convert docx to pdf 
Python :: get Fiscal year 
Python :: merge sort python 
Python :: come fare aprire una pagina web python 
Python :: python count unique values in list 
Python :: python 2 print sep end 
Python :: how to set propee timeline in python 
Python :: python collection 
Python :: merge two arrays python 
Python :: how to use return python 
Python :: all combinations 
ADD CONTENT
Topic
Content
Source link
Name
7+5 =