In this article, I will share with you how to connect the MySQL database in Python using mysql.connector. as you know if you want to make web applications in python the first and very important step is to use any database to store all the records. so, here in this article, I show you how to use the MySQL database in Python.
Python provides mysql.connector
library for connection with MySQL. so, here we also use this library and make connections between MySQL and Python.
After, the connection successfully then you can store, fetch, and update any record in the database help of Python code.
Example
import mysql.connector
from mysql.connector import Error
try:
connection = mysql.connector.connect(host='localhost',
database='myfirstpythonapp',
user='root',
password='root')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("You're connected to database: ", record)
except Error as e:
print("Error while connecting to MySQL", e)
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
i hope you like this article.