安装成功!

1、cmd下执行命令

pip install mysql-connector-python --allow-external mysql-connector-python

如果上面的命令安装失败,可以试试另一个驱动:

pip install mysql-connector

2、python连接mysql

a、导入驱动

>>> import mysql.connector

b、连接数据库

>>>conn = mysql.connector.connect(user='root', password='root', database='test')
>>>cursor = conn.cursor()
>>>cursor.execute('create table t_test_user (id varchar(20) primary key, name varchar(20))')

d、插入一行记录,注意MySQL的占位符是%s:

>>>cursor.execute('insert into t_test_user (id, name) values (%s, %s)', ['1', '奥巴马'])
>>>cursor.rowcount

e、提交事务

>>>conn.commit()
>>>cursor.close()
>>>cursor = conn.cursor()
>>>cursor.execute('select * from user where id = %s', ('1',))
>>>values = cursor.fetchall()
>>>values