导读热词
1、安装方法:
pip install records MysqLclient
2、连接数据库:
1 importrecords2 #3 #root:数据密码
4 #localhost:数据库地址
5 #3306:数据库端口号
6 #mytest:数据库名称
7 db = records.Database('MysqL://root:root@localhost:3306/mytest?charset=utf8')
3、简单的查询:
#查询数据
rows = db.query("select * from user")for r inrows:print(r.id,r.mobile,r.passwd)
4、获取查询结果的方法介绍:
查询到数据以后,可以通过all()方法获取所有的记录,支持3种类型。
◆ 默认是自己封装的RecordCollection对象
◆ 也可以通过as_dict=True参数转成字典形式
◆ 可以通过as_ordereddict=True转成排序字典形式
#获取第一条数据
print(rows.first())#以字典形式获取第一个
print(rows.first(as_dict=True))#查询唯一的一个
print(rows.one())#获取所有数据
print("all方法获取所有数据:",rows.all())#转为json#print(rows.as_dict())
print(rows.all(as_dict=True))#排序字典
print(rows.first(as_ordereddict=True))#导出为具体格式,支持: csv、yaml、json、xls、df(DataFrame)
print(rows.export("yaml"))#转为表格形式
print(rows.dataset)#数据导出到excel文件
with open("user.xlsx","wb") as f:
f.write(rows.export("xlsx"))
5、插入单条数据:
#支持variable定义变量,通过参数传入完成动态传值,在需要动态加载数据的时候非常有用:
user = {"mobile": "13066669999","passwd": "666666"'insert into user(mobile,passwd) values (:mobile,:passwd)'res= db.query(sql,**user)#获取返回结果#print(res.pending)
ifres.pending:print("插入成功")else:print("插入失败")
6、插入多条数据
users =[
{"mobile": "13066660000","passwd": "666666"},{"mobile": "13066660001",{"mobile": "13066660002","passwd": "666666"}
]
sql= 'insert into user(mobile,:passwd)'res= db.bulk_query(sql,users)
参考资料:
https://mp.weixin.qq.com/s?__biz=MzUxMTA3NzgzMQ==&mid=2247491479&idx=1&sn=072c4412dd62ba928e4d1724ad636f9c&chksm=f978633fce0fea29163f527657febee6e9d4e0bd57387df9878adf8d81bd64915d9afe832d64&mpshare=1&scene=1&srcid=&sharer_sharetime=1566521957255&sharer_shareid=07a84e301bcab5607399b81d4cf8c58c&key=7e5df62132e2da6f6ca89e1f9d018cb48763871a895c4685206f95637a38610399e6a10a9db05e9eaa32d52289b4baf3e078f38216e660aa76065a913c6f0f7ca53da6b9c495e9cfb8b472e23913d5af&ascene=1&uin=MjI4MzU0MzI0MQ%3D%3D&devicetype=Windows+10&version=62060844&lang=zh_CN&pass_ticket=hOFgLRgrATK184vvb5U7D27bmc%2FJ6luldzn0Fh9w3qo797LhhxGiOflgYubWpW%2BT
相关文章
总结
如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您喜欢交流学习经验,点击链接加入交流1群:1065694478(已满)交流2群:163560250