Python MySql Create Table

Here, we will create the new table Employee. We have to mention the database name while establishing the connection object.

MySql Create Table

We can create the new table by using the CREATE TABLE statement of SQL. In our database PythonDB, the table Employee will have the four columns, i.e., name, id, salary, and department_id initially.

Table creation example

The following example can be used to create the new table Employee using python.

CopiedCopy Code

import mysql.connector  
myconn = mysql.connector.connect(host = "localhost", user = "root",password = "naveen",database = "PythonDB")  
cur = myconn.cursor()  
  
try:  
    #Creating a table
    dbs = cur.execute("create table Employee(name varchar(20) not null, id int(20) not null primary key, salary float not null, Dept_id int not null)")  
except:  
    myconn.rollback()  
myconn.close()