How to connect with MySql database and execute query in Python?
Aspirant Programmer

Share an example to connect with MySql database and run sql queries in Python.

  • Total 1 Answer
  • 370
Can You answer this question?
Aspirant Programmer

You can connect with MySql database in Python using mysql connector python. You will need to install it first using below command and import it in your program. Refer to below example how to install and execute sql queries.

pip install mysql-connector-python


import mysql.connector
from mysql.connector import Error
    cn = mysql.connector.connect(host='localhost',database='mysqlweb',user='root',password='')
    if cn.is_connected():
        dbinfo = cn.get_server_info()
        print("Connected to MySql database!")
        cursor = cn.cursor()
        cursor.execute("select database();")
        record = cursor.fetchone()
        print("You are connected to: ", record)
except Error as e:
    print("Error while connecting to mysql:", e)
    if (cn.is_connected()):
        print("All connection closed!")


If you face any problem to understand above example at any point, write below your concern and will repond you soon.