python—操作MySQL查询表中数据
生活随笔
收集整理的這篇文章主要介紹了
python—操作MySQL查询表中数据
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
python
# 1、導(dǎo)入mysql
from pymysql import *
# 2、創(chuàng)建數(shù)據(jù)庫(kù)lianjie
conn = connect(host='localhost',port=3306,user='root',password='root',db='mytestdb',charset='utf8')
print(conn)
# 3、打開游標(biāo)
cur=conn.cursor()
# 4、執(zhí)行sql語句
# 編寫sql語句
# 查詢數(shù)據(jù)時(shí)為了節(jié)約內(nèi)存,不要用*,而要指定具體的字段,另外要指定查詢條件,現(xiàn)在查詢條數(shù)
sql="select sno,sname,sex,age,enterdate,classname,email from t_student1 where age>%s"
params=(30)
# 執(zhí)行sql語句
cur.execute(sql,params)# todo 獲取1條數(shù)據(jù),每次執(zhí)行cur.fetchone()語句,游標(biāo)都會(huì)向下走,獲取到新的數(shù)據(jù)
# result=cur.fetchone()
# print(result)
# result=cur.fetchone()
# print(result)
# result=cur.fetchone()
# print(result)
# todo 獲取所有的數(shù)據(jù)
result1=cur.fetchall()
print(result1)
# todo 獲取多條數(shù)據(jù)
# result1=cur.fetchmany(2) #取指定條數(shù)據(jù)
# print(result1)# 5、關(guān)閉游標(biāo)
cur.close()
# 6、關(guān)閉連接
conn.close()
查詢數(shù)據(jù)時(shí)為了節(jié)約內(nèi)存,不要用*,而要指定具體的字段,另外要指定查詢條件,現(xiàn)在查詢條數(shù)
獲取1條數(shù)據(jù),result=cur.fetchone()
總結(jié)
以上是生活随笔為你收集整理的python—操作MySQL查询表中数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 串行、并行、并发总结
- 下一篇: 【python】算法引入及算法特性和时间