python-mysqlHow can I use Python to yield results from a MySQL database?
Using Python to yield results from a MySQL database is a fairly simple process. The most important step is to install the appropriate Python library for interacting with MySQL. The most popular library for this purpose is MySQL Connector/Python.
Once the library is installed, the next step is to create a connection object. This object holds all the necessary information to connect to the MySQL database. The following code block demonstrates how to create a connection object:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
print(mydb)
# Output: <mysql.connector.connection.MySQLConnection object at 0x7f9f7d9b4eb8>
After the connection is established, a cursor object can be created. This object allows the user to execute SQL queries. The following code block demonstrates how to create a cursor object and execute a query:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM customers")
myresult = mycursor.fetchall()
for x in myresult:
print(x)
# Output:
# ('John', 'Highway 21')
# ('Peter', 'Lowstreet 4')
# ('Amy', 'Apple st 652')
# ('Hannah', 'Mountain 21')
Code explanation
import mysql.connector
- Imports the library for interacting with MySQL.mydb = mysql.connector.connect(host="localhost", user="yourusername", passwd="yourpassword")
- Creates a connection object with the necessary information to connect to the MySQL database.mycursor = mydb.cursor()
- Creates a cursor object.mycursor.execute("SELECT * FROM customers")
- Executes a SQL query.myresult = mycursor.fetchall()
- Fetches all the results from the query.for x in myresult: print(x)
- Prints each result from 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...