How to connect with MySql database and execute query in Python?
author
,
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?
author
,
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

Example:

import mysql.connector
from mysql.connector import Error
try:
    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)
finally:
    if (cn.is_connected()):
        cursor.close()
        cn.close()
        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.