Python MySql - Connect to Database



Python MySQLdb provides MySQLdb.connect() function to open a database connection. This function takes multiple parameters and returns a connection object to do database operations.

Syntax

db = mysql.connector.connect(host="localhost",user="root",password="root@123")
Sr.No. Parameter & Description
1

host

Optional − The host name running the database server. If not specified, then the default value will be localhost:3306.

2

username

Optional − The username accessing the database. If not specified, then the default will be the name of the user that owns the server process.

3

password

Optional − The password of the user accessing the database. If not specified, then the default will be an empty password.

4

database

Optional − database name on which query is to be performed.

5

port

Optional − the port number to attempt to connect to the MySQL server..

6

unix_socket

Optional − socket or named pipe that should be used.

There are several other properties as well. Refer MySQL Connector for complete reference.

You can disconnect from the MySQL database anytime using another connection object function close().

Syntax

db.close()

Example - Connecting to MySql Server

Try the following example to connect to a MySQL server −

Copy and paste the following example as main.py −

main.py

import mysql.connector

# Open database connection
db = mysql.connector.connect(host="localhost",user="root",password="root@123")

# prepare a cursor object using cursor() method
cursor = db.cursor()

# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()
if data:
   print('Version available: ', data)
else:
   print('Version not retrieved.')

# disconnect from server
db.close()

Output

Execute the main.py script using python and verify the output.

(myenv) D:\Projects\python\myenv>py main.py
Version available:  ('8.0.43',)
Advertisements