本篇咱们主要对mysql的查询进行讲解。查询在数据库中的应用是最为普遍的,好比单表查询、多表查询、子查询、分组查询等等、接下来重点了解一下python结合mysql是如何实现查询的?python
首先咱们来看对单条数据的查询:mysql
def select(): '''查询语句''' con = conn() # 建立游标 cur = con.cursor() sql = "select * from USER WHERE id=%s"
params = (1,) cur.execute(sql,params) # 执行语句 data = cur.fetchone() print (data) cur.close() # 关闭游标链接池 con.close() # 关闭数据库链接池 select()
查询后的结果以下:sql
C:\Python27\python2.exe D:/project/JieKou/page/mysqTests.py (1L, 'fighter', 'admin', 'sanpang') Process finished with exit code 0
1L咱们能够把它忽略,不须要考虑。接下来咱们实现对多条数据,也就是批量数据的查询是如何操做的???数据库
def selectMany(): '''查询语句''' con = conn() # 建立游标 cur = con.cursor() sql = "select * from USER" cur.execute(sql) # 执行语句 data = cur.fetchall() for item in data: print (item) cur.close() # 关闭游标链接池 con.close() # 关闭数据库链接池 selectMany()
查看查询后的结果:fetch
C:\Python27\python2.exe D:/project/JieKou/page/mysqTests.py (1L, 'fighter', 'admin', 'sanpang') (2L, 'fighter01', 'admin', 'sanpang') (3L, 'fighter02', 'admin', 'sanpang')
截图结果:spa
而后咱们对数据进行修改操做:3d
def update(): '''查询语句''' con = conn() # 建立游标 cur = con.cursor() sql = "update user set username=%s WHERE id=%s"
params = ('haha',2) cur.execute(sql,params) # 执行语句 con.commit() cur.close() # 关闭游标链接池 con.close() # 关闭数据库链接池 update()
修改后的结果以下:code
在对数据进行删除操做:blog
def delete(): '''查询语句''' con = conn() # 建立游标 cur = con.cursor() sql = "delete from USER where id=%s"
params = (1,) cur.execute(sql,params) # 执行语句 con.commit() #必定要执行 cur.close() # 关闭游标链接池 con.close() # 关闭数据库链接池 delete()
删除结果以下:it
ok,mysql的查询和修改、删除的场景咱们就演示完了,,,,,