我是靠谱客的博主 安静帅哥,这篇文章主要介绍Python连接MySQL数据库进行增删查改,现在分享给大家,希望可以做个参考。

1.连接数据库

我是用的python版本是3.6.6,就得先安装PyMySQL模块;

如果是Python2中则使用mysqldb模块,也需先安装。

安装PyMySQL

C:Usersasus>pip3 install PyMySQL

Collecting PyMySQL

Downloading https://files.pythonhosted.org/packages/a7/7d/682c4a7da195a678047c8f1c51bb7682aaedee1dca7547883c3993ca9282/PyMySQL-0.9.2-py2.py3-none-any.whl (47kB)  100% |████████████████████████████████| 51kB 104kB/s

开始使用:

复制代码
1
2
3
4
5
import pymysql #打开数据库连接 db = pymysql.connect('192.168.1.103','root','mysql','py_peewee')

插入数据前确保数据库中已经存在相应的table

插入一条数据:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
import pymysql #引入模块 #打开数据库连接 db = pymysql.connect('192.168.1.103','root','mysql','py_peewee') #创建一个游标 cursor = db.cursor() sql_insert="INSERT INTO person(NAME,PASSWD,EMAIL,GENDER,BIRTHDAY,IS_ADMIN)" "VALUES('Asda','12321','AsSs@33',2,STR_TO_DATE('06/05/2017','%m/%d/%Y'),TRUE)" #执行sql语句 cursor.execute(sql_insert) # 提交到数据库执行 db.commit() #进行提交

条件查找语句

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import pymysql #打开数据库连接 db = pymysql.connect('192.168.1.103','root','mysql','py_peewee') cursor = db.cursor() sql = "select * from person where is_admin=true" cursor.execute(sql) #fetchall() 查询结果为多行数据,fetchone()函数之获取一条数据,结果是个对象 results = cursor.fetchall() #结果类型 print(type(results)) #通过控制台可以看到results的类型是<class 'tuple'>元组,所以通过操作tuple方式操作查询结果,而且内部元素也是tuple # print(results[0]) # print(results[1]) # print(results[2]) #循环输出 for row in results: print(row[0]) print(row[1]) print(row[2]) print(row[3]) #关闭连接 db.close()

删除操作:

复制代码
1
2
3
4
5
6
7
8
9
10
11
import pymysql #打开数据库连接 db = pymysql.connect('192.168.1.103','root','mysql','py_peewee') cursor = db.cursor() sql = "DELETE from person where id=2" cursor.execute(sql) db.commit() #关闭连接 db.close()

修改操作:

复制代码
1
2
3
4
5
6
7
8
9
10
11
import pymysql #打开数据库连接 db = pymysql.connect('192.168.1.103','root','mysql','py_peewee') cursor = db.cursor() sql = "update person SET name='ppp' where name='ab'" cursor.execute(sql) db.commit() #关闭连接 db.close()

以上的操作方式都是比较简单底层的,没有引入框架,有点类似Java的JDBC操作

同时上面的sql执行方式与Java的Statement对象相同,都是进行sql字符串拼接,存在sql注入漏洞




最后

以上就是安静帅哥最近收集整理的关于Python连接MySQL数据库进行增删查改的全部内容,更多相关Python连接MySQL数据库进行增删查改内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(81)

评论列表共有 0 条评论

立即
投稿
返回
顶部