Create MySQL Table using Python
Create MySQL Table using Python is one of the simplest query that we can run using Python. Syntax of create table command is as follows
CREATE TABLE tableName ( column1 datatype(size) constrainsts, column2 datatype(size) constrainsts, ....... ...... );
Example Table that we will create using Python is as follows
+--------+------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +--------+------------+------+-----+---------+-------+ | id | int(6) | YES | | NULL | | | name | char(30) | YES | | NULL | | | dept | char(30) | YES | | NULL | | | salary | float(7,2) | YES | | NULL | | +--------+------------+------+-----+---------+-------+
The command to create the above table on MySQL prompt is as follows
mysql> create table employee ( id int(6), name char(30), dept char(30), salary float(7,2)); Query OK, 0 rows affected (0.02 sec)
Python Program to Create Table
This is a suggestive python program to create an employee Table
import mysql.connector conn = mysql.connector.connect(host='localhost',user='root',password='',database="school") cursor = conn.cursor() query = "create table employee ( id int(6), name char(30), dept char(30), salary float(7,2));" cursor.execute(query) conn.close() print('Table created successfully') Output $ python -u "c:\Users\rakesh\Desktop\database_connection.py" Table created successfully
NOTE
1. MySQL connector module must be installed in your system
2. School database must be there before execution of this Python Script
3. MySQL server must be active on its default port ie 3306.