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
  2. 本地开启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() --关闭连接
上一篇:杂七杂八


下一篇:为你的博客添加几分色彩