Category Archives: Python

Python program to create a table in MySQL Connector

Using MySQL Connector create a table in the database using Python

Following is the Python program used to create a table in the database testdb as shown below:


-- Import the mysql connector
import mysql.connector

-- Use Exception handling
try:
-- Create a connection with Mysql database 
    connection = mysql.connector.connect(host='localhost',
                                         database='testdb',
                                         user='root',
                                         password='password',port=3307)

-- Write the create table syntax used in SQL
    v_query = """CREATE TABLE testtable ( 
                             Id int(11) NOT NULL,
                             Name varchar(250) NOT NULL,
                             PRIMARY KEY (Id)) """

-- Execute the query
    cursor = connection.cursor()
    result = cursor.execute(v_query)
    print("Table created successfully ")


--If error occurred pring the error
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")