python-mysqlHow can I use the Python MySQL API to interact with a MySQL database?
The Python MySQL API provides a number of functions that can be used to interact with a MySQL database. To use the API in a Python program, it must first be imported using the import
statement.
import mysql.connector
Once imported, a connection to the MySQL database can be established using the connect()
function. This function requires parameters for the hostname, username, password, and database name.
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="mydatabase"
)
Once a connection is established, a cursor object can be created to execute SQL statements.
mycursor = mydb.cursor()
The execute()
method of the cursor object can be used to execute SQL statements.
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output example
(1, 'John', 'Highway 21')
(2, 'Peter', 'Lowstreet 4')
(3, 'Amy', 'Apple st 652')
(4, 'Hannah', 'Mountain 21')
(5, 'Michael', 'Valley 345')
(6, 'Sandy', 'Ocean blvd 2')
(7, 'Betty', 'Green Grass 1')
(8, 'Richard', 'Sky st 331')
(9, 'Susan', 'One way 98')
(10, 'Vicky', 'Yellow Garden 2')
(11, 'Ben', 'Park Lane 38')
(12, 'William', 'Central st 954')
(13, 'Chuck', 'Main Road 989')
(14, 'Viola', 'Sideway 1633')
The Python MySQL API also provides functions for creating, reading, updating, and deleting records from the database.
Code explanation
import mysql.connector
- imports the Python MySQL APImydb = mysql.connector.connect()
- establishes a connection to the MySQL databasemycursor = mydb.cursor()
- creates a cursor object to execute SQL statementsmycursor.execute()
- executes SQL statementsmycursor.fetchall()
- retrieves the results of the SQL query
Helpful links
More of Python Mysql
- How can I connect Python to a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How can I compare and contrast using Python with MySQL versus PostgreSQL?
- How do I use Python to perform an INSERT ON DUPLICATE KEY UPDATE query in MySQL?
- How do I insert the current datetime into a MySQL database using Python?
- How can I use Python to yield results from a MySQL database?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
- How do I connect to XAMPP MySQL using Python?
- How do I set up a secure SSL connection between Python and MySQL?
- How can I get the row count of a MySQL table using Python?
See more codes...