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 can I connect Python to a MySQL database?
- How can I use Python and MySQL to generate a PDF?
- How can I access MySQL using Python?
- How can I connect to MySQL using Python?
- How can I use Yum to install the MySQLdb Python module?
- How can I connect Python to a MySQL database using an Xserver?
- How can I host a MySQL database using Python?
- How do I access MySQL using Python?
- How can I connect Python and MySQL?
- How do I download MySQL-Python 1.2.5 zip file?
See more codes...