1.安装MySQL驱动
MySQL服务器以独立的进程运行,并通过网络对外服务,所以,需要支持Python的MySQL驱动来连接到MySQL服务器。MySQL官方提供了mysql-connector-python驱动,但是安装的时候需要给pip命令加上参数--allow-external:
$pip install mysql-connector-python --allow-external mysql-connector-python
如果上面的命令安装失败,可以试试下面这个驱动:
$pip install mysql-connector
下面是连接到MySQL服务器的代码
# 导入MySQL驱动:
>>>importmysql.connector# 注意把password设为你的root口令:
>>>conn = mysql.connector.connect(user='root', password='password', database='test')
>>>cursor = conn.cursor()# 创建user表:
>>>cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')# 插入一行记录,注意MySQL的占位符是%s:
>>>cursor.execute('insert into user (id, name) values (%s, %s)', ['1','Michael'])
>>>cursor.rowcount1# 提交事务:
>>>conn.commit()
>>>cursor.close()# 运行查询:
>>>cursor = conn.cursor()
>>>cursor.execute('select * from user where id = %s', ('1',))
>>>values = cursor.fetchall()
>>>values[('1','Michael')]# 关闭Cursor和Connection:
>>>cursor.close()
True
>>>conn.close()
注意: