dedtech.info

Information about computer technology.

Create A MySQL Table With Python

This blog post will explain how to create a MySQL table with python. First, the required library has to be imported.

import mysql.connector

The connection to the database has to be established.

sql = mysql.connector.connect(host="localhost", user="user", password="pass", database="exampledb")

A cursor to parse database table rows and columns has to be created.

cursor = sql.cursor()

The variable employee will hold the MySQL query needed to create a table.

employee = """CREATE TABLE EMPLOYEE(
                   ID INT,
                   NAME  VARCHAR(20)
                   )"""

The function below will execute the MySQL query that is stored in the employee variable.

cursor.execute(employee)

The statements below will close the database connection and close the cursor object.

sql.close()
cursor.close()

This is what the whole source code looks like.

import mysql.connector
sql = mysql.connector.connect(host="localhost", user="user", password="pass", database="exampledb")
cursor = sql.cursor()
 
employee = """CREATE TABLE EMPLOYEE(
                   ID INT,
                   NAME  VARCHAR(20)
                   )"""
 
cursor.execute(employee)
sql.close()
cursor.close()

One thought on “Create A MySQL Table With Python

Leave a Reply to tt88bet Cancel reply

Your email address will not be published. Required fields are marked *