Operate MySQL Using Python MYSQLdb

In this tutorial, we will introduce the way to connet mysql server, drop and create mysql table using python mysqldb library.

1. Install python mysqldb library.

conda install -c anaconda mysql-python

conda install -c anaconda mysql-connector-python

or

pip install MySQL-python

pip install MySQL-python-connector

2. Import mysqldb

import MYSQLdb

3. Connect mysql server using python mysqldb

#Trying to connect  
try: 
    db_connection= MySQLdb.connect("Hostname","dbusername","password","dbname") 
# If connection is not successful 
except: 
    print("Can't connect to database")
# If Connection Is Successful 
print("Connected")

4. Create a cursor to operate mysql

cursor = db.cursor()

5. Drop a table

We can execute a drop sql statement.

# Drop table if it already exist using execute() 
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")

6. Create a table

We also can execute a create table sql statement to create a table in mysql server.

sql =  'CREATE TABLE EMPLOYEE ( 
         FNAME  CHAR(20) NOT NULL, 
         LNAME  CHAR(20), 
         AGE INT ) '
  
cursor.execute(sql) #table created

7. Close mysql

# disconnect from server 
db.close()