python-mysqlHow can I write a Python MySQL query example?
To write a Python MySQL query example, you can use the MySQLdb
module. This module provides an interface to the MySQL database server from Python.
Below is a simple example of how to execute a query using this module.
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","user","password","database")
# 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()
print "Database version : %s " % data
# disconnect from server
db.close()
The output of this code would be:
Database version : 5.6.17
Code explanation
import MySQLdb
- imports the MySQLdb moduledb = MySQLdb.connect("localhost","user","password","database")
- connects to the MySQL servercursor = db.cursor()
- creates a cursor objectcursor.execute("SELECT VERSION()")
- executes the SQL querydata = cursor.fetchone()
- fetches a single row from the result setprint "Database version : %s " % data
- prints the result from the querydb.close()
- closes the connection to the MySQL server
For more information, please see the MySQLdb documentation.
More of Python Mysql
- How do I connect to XAMPP MySQL using Python?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I install the MySQL-Python (Python 2.x) module?
- How do I download MySQL-Python 1.2.5 zip file?
- How can I connect Python to a MySQL database?
- How do I use Python to update multiple columns in a MySQL database?
- How do I use Python to query MySQL with multiple conditions?
- How do I use Python to authenticate MySQL on Windows?
- How do I use a Python MySQL refresh cursor?
- How do I use a cursor to interact with a MySQL database in Python?
See more codes...