×

Python Tutorial

Python Basics

Python I/O

Python Operators

Python Conditions & Controls

Python Functions

Python Strings

Python Modules

Python Lists

Python OOPs

Python Arrays

Python Dictionary

Python Sets

Python Tuples

Python Exception Handling

Python NumPy

Python Pandas

Python File Handling

Python WebSocket

Python GUI Programming

Python Image Processing

Python Miscellaneous

Python Practice

Python Programs

Create MySQL Table in Python

Python MySQL | Create Table: In this tutorial, we will learn about the MySQL table creation with the help of Python program. By Shivang Yadav Last updated : April 21, 2023

Using Python, we can access and manipulate databases and perform other backend tasks. Python has a library named pymysql to perform the MySQL task and execute the queries. One database manipulation method that can be performed using Python is creating a new table on the server using Python.

How to Create MySQL Table in Python?

The following steps are used to create a MySQL table:

  1. Import the MySQL connect using import statement.
    import  pymysql as ps
  2. Connect to the database using connect() method.
    n = ps.connect(host='localhost',port=3306,user='root',password='123',db='tata')
  3. Create a command to execute the query using the cursor() method.
    query = "create table products(productid varchar(10) primary key,productname varchar(45),productrate decimal(10),mfdate date)"
    
  4. Write the query to be executed to perform the task.
  5. Execute the query using the execute() method.
    cmd.execute(query)

Python Program to Create MySQL Table

import pymysql as ps

try:
    # cn is an object which hold the reference of database engine
    cn = ps.connect(host="localhost", port=3306, user="root", password="123", db="tata")

    """
    cursor() is used to create command
    object, which is use to supply sql queries
    to database engine"""
    
    cmd = cn.cursor()

    query = "create table products(productid varchar(10) primary key,productname varchar(45),productrate decimal(10),mfdate date)"

    cmd.execute(query)

    print("Table Created..")

    cn.commit()
    cn.close()
except Exception as e:
    print("Error:", e)

Output

Table Created..

On the server the table is created based on the query.

Python MySQL Programs »


Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.