1 安裝 MySQL connector
mysql-connector-python支持Linux靖秩、Mac OS X和Windows系統(tǒng)。
mysql-connector-python的下載地址http://dev.mysql.com/downloads/connector/python/。
我以Ubuntu系統(tǒng)Python2.7為例:
方法一:使用apt安裝:
$ sudo apt install python-mysql.connector
1
$ sudo apt install python-mysql.connector
方法二:使用pip安裝:
$ sudo pip install mysql-connector-python
方法三:安裝最新版
$ wget http://cdn.mysql.com//Downloads/Connector-Python/mysql-connector-python-cext_2.1.3-1ubuntu15.04_amd64.deb
$ sudo dpkg -i mysql-connector-python-cext_2.1.3-1ubuntu15.04_amd64.deb
查看安裝的mysql-connector-python版本:
2 連接MySQL
連接本地MySQL數(shù)據(jù)庫:
import mysql.connector
conn = mysql.connector.connect(
user='root',
password='test1234',
host='127.0.0.1',
database='test')
關(guān)閉數(shù)據(jù)庫
conn.close()
如果提供的用戶、數(shù)據(jù)庫不對,會(huì)輸出如下錯(cuò)誤信息:
Traceback (most recent call last):
File "test.py", line 7, in <module>
database='test')
File "/usr/lib/python2.7/dist-packages/mysql/connector/init.py", line 162, in connect
return MySQLConnection(*args, kwargs)
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 129, in init
self.connect(kwargs)
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 454, in connect
self._open_connection()
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 421, in _open_connection
self._ssl)
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 204, in _do_auth
self._auth_switch_request(username, password)
File "/usr/lib/python2.7/dist-packages/mysql/connector/connection.py", line 240, in _auth_switch_request
raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
3 執(zhí)行SQL語句
import mysql.connector
conn = mysql.connector.connect(
user='root',
password='test1234',
host='127.0.0.1',
database='test')
cur = conn.cursor()
要執(zhí)行的SQL語句
query = ("SELECT * FROM sometable")
執(zhí)行查詢
cur.execute(query)
for (id, name, class, score) in cur:
print("{}, {}, {}, {}".format(id, name,class,score))
cur.close()
conn.close()