Python & MySQL - Select Database Example



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

Syntax

db = MySQLdb.connect(host, username, passwd, dbName, port, socket);

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

passwd

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

4

dbName

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

socket

Optional − socket or named pipe that should be used.

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

Syntax

db.close()

Example

Try the following example to connect to a MySQL database −

Copy and paste the following example as mysql_example.py −

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","root","root@123", "TUTORIALS")

# 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 mysql_example.py script using python and verify the output.

py mysql_example.py
Version available:  ('8.0.23',)
Advertisements