python-mysqlHow do I use a cursor to interact with a MySQL database in Python?
Using a cursor to interact with a MySQL database in Python is easy and efficient. To do this, you'll need to import the MySQL Connector library for Python.
import mysql.connector
Once the library is imported, you can create a connection to the MySQL database using the connect()
method.
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
Next, you can create a cursor object from the connection using the cursor()
method.
mycursor = mydb.cursor()
After that, you can use the cursor to execute SQL queries. For example, you can use the execute()
method to create a table.
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
Finally, you can use the fetchall()
method to get the results of a query.
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
Output example
('John', 'Highway 21')
('Peter', 'Lowstreet 4')
('Amy', 'Apple st 652')
('Hannah', 'Mountain 21')
Code explanation
import mysql.connector
: This imports the MySQL Connector library for Python.mydb = mysql.connector.connect(host="localhost", user="yourusername", passwd="yourpassword")
: This creates a connection to the MySQL database using theconnect()
method.mycursor = mydb.cursor()
: This creates a cursor object from the connection using thecursor()
method.mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")
: This uses theexecute()
method to create a table.mycursor.execute("SELECT * FROM customers")
: This uses theexecute()
method to execute a query.myresult = mycursor.fetchall()
: This uses thefetchall()
method to get the results of a query.for x in myresult: print(x)
: This prints the results of the query.
Helpful links
More of Python Mysql
- How do I download MySQL-Python 1.2.5 zip file?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How do I use Python to query MySQL with multiple conditions?
- How can I install the MySQL-Python (Python 2.x) module?
- How can I access MySQL using Python?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
- How can I use Python to make a MySQL request?
- How do I execute a query in MySQL using Python?
See more codes...