一、需要在.env中配置数据库的主机地址,账号,密码,端口号等信息

 

二、写查询函数

from django.db.utils import ConnectionHandler 

connections = ConnectionHandler()





def rule_dos(self): """ 拿到rule中剂型name与id的对应关系 """ with connections['default'].cursor() as cr: cr.execute(""" select t1.id,t1.name from mdd_rule.knowledge_dosageform as t1 where TRUE """) rows = cr.fetchall() # 拿到所有数据 dic = {} for i in rows: dic[i[1]] = i[0] return dic

fetchone() :

返回单个的元组,也就是一条记录(row),如果没有结果 则返回 None


fetchone()用法:

cur.execute("select host,user,password from user where user='%s'" %acc)
jilu = cur.fetchone() ##此时 通过 jilu[0],jilu[1],jilu[2]可以依次访问host,user,password


fetchall() :

返回多个元组,即返回多个记录(rows),如果没有结果 则返回 ()

需要注明:在mysql中是NULL,而在python中则是None

fetchall()用法:

cur.execute("select * from user")

如果select本身取的时候有多条数据时:

cursor.fetchone():将只取最上面的第一条结果,返回单个元组如('id','title'),然后多次使用cursor.fetchone(),依次取得下一条结果,直到为空。

cursor.fetchall() :将返回所有结果,返回二维元组,如(('id','title'),('id','title')),

如果select本身取的时候只有一条数据时:

cursor.fetchone():将只返回一条结果,返回单个元组如('id','title')。

cursor.fetchall() :也将返回所有结果,返回二维元组,如(('id','title'),),

python在mysql在使用fetchall或者是fetchone时,综合起来讲,fetchall返回二维元组(元组中含有元组),fetchone只返回一维元组

 

posted on 2021-09-13 11:10  輪滑少年  阅读(362)  评论(0编辑  收藏  举报