Python下操作Mysql数据库
默认情况下,MySQLdb包是没有安装的
安装mysql-python
pip install MySQL-python
python操作mysql数据库
# 导入MySQL驱动:
> import mysql.connector
# 注意把password设为你的root口令:
'root', password='password', database='test') > conn = mysql.connector.connect(user=
> cursor = conn.cursor()
# 创建user表:
'create table user (id varchar(20) primary key, name varchar(20))') > cursor.execute(
# 插入一行记录,注意MySQL的占位符是%s:
'insert into user (id, name) values (%s, %s)', ['1', 'Michael']) > cursor.execute(
> cursor.rowcount
1
# 提交事务:
> conn.commit()
cursor.close()
# 运行查询:
> cursor = conn.cursor()
'select * from user where id = %s', ('1',)) > cursor.execute(
> values = cursor.fetchall()
> values
[('1', 'Michael')]
# 关闭Cursor和Connection:
> cursor.close()
True
> conn.close()