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 use Python to update multiple columns in a MySQL database?
- How do I use Python to show the MySQL processlist?
- How do I format a date in MySQL using Python?
- How can I connect to MySQL using Python?
- How can I connect Python to a MySQL database?
- How do I show databases in MySQL using Python?
- How can I use Python to retrieve data from MySQL?
- How can I use Python to interact with a MySQL database using YAML?
- How do I use Python to authenticate MySQL on Windows?
- How can I use Python and MySQL to create a login system?
See more codes...