首先声明一下,我用的是Windows系统!
1、在Python中对mysql数据库进行操作首先要导入pymysql模块,默认情况下,Python中是没有安装这个模块的,
可以在Windows的命令行中用pip install pymysql来安装(注意要连网)。除了pymysql模块外,还可以用其他模块。
2、在Python中数据库表的创建就不细说了,我习惯是在navicat中创建。
3、查找数据
(1)不带条件的查找
import pymysqlconn = pymysql.connect(user='root', password='root', database='gaokao', charset='utf8') cursor = conn.cursor() query = ('select id, name from my_school') cursor.execute(query) for (id, name) in cursor:print(id, name) cursor.close() conn.close()
查找结果如下:
(2)带条件的查找
import pymysqlconn = pymysql.connect(user='root', password='root', database='gaokao', charset='utf8') cursor = conn.cursor() #不论是什么数据类型,占位符都用%s query = ('select id, name from my_school where id > %s and id < %s') cursor.execute(query, (7, 12)) for (id, name) in cursor:print(id, name) cursor.close() conn.close()
查找结果如下:
3、插入数据
import pymysqlconn = pymysql.connect(user='root', password='root', database='gaokao', charset='utf8') cursor = conn.cursor()query = ('insert into my_school(id, name) values(%s, %s)') cursor.execute(query, (16, '杭州电子科技大学')) conn.commit() #只要是修改了表内容的操作,后面一定要提交,否则不起作用 cursor.close() conn.close()
- 修改后的结果如下:
4、修改数据
import pymysqlconn = pymysql.connect(user='root', password='root', database='gaokao', charset='utf8') cursor = conn.cursor() query = ('update my_school set name = %s where id = %s') cursor.execute(query, ('兰州大学', 6)) conn.commit() #同样不要忘记提交 cursor.close() conn.close()
修改后的结果如下:
5、删除数据
import pymysqlconn = pymysql.connect(user='root', password='root', database='gaokao', charset='utf8') cursor = conn.cursor() query = ('delete from my_school where id > %s') cursor.execute(query, 10) conn.commit() cursor.close() conn.close()
- 执行后的效果如下:
结束:Python操作mysql确实是相当方便的