7.1 Connecting to a MySql database from Python

  1. install mysql-connector-python
$ sudo pip3 install --extra-index-url https://pypi.python.org/pypi/mysql-connector-python/2.0.4 mysql-connector-python
  1. 本地开启mysql数据库,在terminal中输入python3,导入模块并创建连接
>>> import mysql.connector
>>> conn = mysql.connector.connect(user='root', password='mysql', database='engineer')
>>> cursor = conn.cursor()
>>> cursor.execute('select * from user')
>>> values = cursor.fetchall()
>>> values
[('1', '1', '1', '1'), ('2', '2', '2', '2')]
>>> cursor.close() --关闭游标
True
>>> conn.close() --关闭连接

你可能感兴趣的:(7.1 Connecting to a MySql database from Python)