Python connects to MySQL database (Debian)
The following is a Python 2.* version of the installation method, Mysql-python temporarily does not support Python 3.* version
What to do in advance:
Install Setuptools, run in terminal
sudo python
install pip, download "get_pip.py", run
python get_pip.py
Run the following command to install the necessary packages
sudo apt-get install python-dev libmysqld-dev libmysqlclient-dev
Official installation:
install MySQL (some system comes with it):
sudo apt-get install mysql-server
download Mysql-python and unzip, go to the extracted folder, Run command
python setup.py build python setup.py install
Use
Code instance (from W3cschool), connect MySQL's testdb database, output MySQL version number:
# Encoding:utf-8#!/usr/bin/pythonImportMySQLdb# Open database connectiondb = MySQLdb.connect ("localhost","TestUser","test123","TESTDB")# Get an action cursor using the cursor () methodcursor = Db.cursor ()# Execute SQL statements using the Execute methodCursor.execute ("Select VERSION ()")# Use the Fetchone () method to get a database. data = Cursor.fetchone ()Print "Database version:%s"% data# Close the database connectionDb.close ()
?
Python connects to MySQL database (Debian)