Python对MySQL数据库的操作
目录
Python对MySQL数据库的操作
Python中,可以使用MySQLdb模块连接到MySQL数据库,对MySQL数据库进行操作
【 第一步 】
参考文档:
【 第二步 】 连接到
- 创建数据库
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 5
Server version: 5.5.19 MySQL Community Server (GPL)
mysql>
#创建数据库
mysql> create database python;
Query OK, 1 row affected (0.09 sec)
#使用数据库
mysql> use python;
Database changed
#创建表
mysql> create table people (name VARCHAR(30), age INT, sex CHAR(1));
Query OK, 0 rows affected (0.44 sec)
#插入数据
mysql> insert into people values('Tom', 20, 'M');
Query OK, 1 row affected (0.13 sec)
mysql> insert into people values('Jack', NULL, NULL);
Query OK, 1 row affected (0.06 sec)
#查看数据
mysql> select * from people;
+------+------+------+
| name | age | sex |
+------+------+------+
| Tom | 20 | M |
| Jack | NULL | NULL |
+------+------+------+
2 rows in set (0.05 sec)
- 安装MySQLdb
官方网站:
下载与自己操作系统,Python版本吻合的exe文件,点击下一步即可完成安装。如下,则表示安装成功!
>>> import MySQLdb
>>>
- 在Python中使用MySQL
import MySQLdb # 导入MySQLdb模块
db = MySQLdb.connect(host = 'localhost', # 连接到数据库,服务器为本机
user = 'root', # 用户名为:root
passwd = '1234', # 密码为:1234
db = 'python') # 数据库:python
cur = db.cursor() # 获得数据库游标
cur.execute('insert into people values("Jee", 21, "F")') # 执行SQL,添加记录
res = cur.execute('delete from people where age=20') # 执行SQL,删除记录
db.commit() # 提交事务
res = cur.execute('select * from people') # 执行SQL, 获取记录
res = cur.fetchall() # 获取全部数据
print(res) # 打印数据
cur.close() # 关闭游标
db.close() # 关闭数据库连接
具体API定义,请参考: