当前位置: 首页 > news >正文

中国三北防护林体系建设网站机器人编程培训机构排名

中国三北防护林体系建设网站,机器人编程培训机构排名,湖北省建设厅的网站,提供网站建设空间文章目录同步操作同步连Mysql同步连redis同步连mongodb异步操作异步连mysql异步连redis异步连mongodb同步操作 同步连Mysql python 连接mysql可以使用pymysql、mysqlclient等。 安装: # win pip install pymysql 连接mysql: # __author__ "laufing"…

文章目录

  • 同步操作
    • 同步连Mysql
    • 同步连redis
    • 同步连mongodb
  • 异步操作
    • 异步连mysql
    • 异步连redis
    • 异步连mongodb

同步操作

同步连Mysql

python 连接mysql可以使用pymysql、mysqlclient等。

安装

# win
pip install pymysql 

连接mysql:

# __author__ = "laufing"
import pymysql# 连接
conn = pymysql.connect(host="localhost", port=3306, user="lauf", password="xxx", # 太长直接换行database="test_lauf", charset="utf8")
# 开启事务
conn.begin()# 获取游标
cursor = conn.cursor()
# 执行操作
cursor.execute("create table if not exists stu(id int primary key auto_increment, name varchar(50) unique , age int, price decimal, ""birth date)engine=innodb;") # innodb 支持事务、外键;行级锁
cursor.execute("insert into stu(id, name, age, price, birth) values (1, 'jack', 12, 20.4, '2000-01-20'),""(2, 'lucy', 18, 300.5, '1990-05-23');")# ...# 尝试回滚  不会删除已创建的表
# conn.rollback()# 提交
conn.commit()# 最后关闭
cursor.close()
conn.close()

以上cursor操作部分,可以使用with来操作。

自定义上下文管理器,实现数据库的连接:

  1. 进入with作用域前,连接db、开启事务、 并获取游标;
  2. with作用域实现sql操作;
  3. with作用域结束退出时
# __author__ = "laufing"
import pymysql# 自定义上下文管理器
class LaufConnectMysql():def __init__(self, **kwargs):# kwargs 收集 pymysql连接db的参数  + transaction: booltransaction = kwargs.pop("transaction")self.conn = pymysql.connect(**kwargs)self.cursor = Noneif transaction:# 开启事务self.conn.begin()def __enter__(self):""" 进入with作用域前 即执行"""print("进入with作用域前的准备工作(as)...")# 返回什么,with xxx as xxx, as 后面拿到的就是什么# 返回cursor游标对象self.cursor = self.conn.cursor()self.cursor.conn = self.connreturn self.cursordef __exit__(self, exc_type, exc_val, exc_tb):print("退出with作用域的收尾工作...")# 关闭游标self.cursor.close()# 关闭连接self.conn.close()# 防止内存泄漏if __name__ == '__main__':# 连接db的参数kw_args = {"host": "localhost","port": 3306,"user": "lauf","password": "xxx","database": "test_lauf","charset": "utf8","transaction": True}# with 操作with LaufConnectMysql(**kw_args) as cursor:  #print("with作用域:", cursor, type(cursor))# 执行操作try:cursor.execute("create table if not exists stu(id int primary key auto_increment, name varchar(50) unique , age int, price decimal, ""birth date)engine=innodb;") # innodb 支持事务、外键;行级锁cursor.execute("insert into stu(id, name, age, price, birth) values (1, 'jack', 12, 20.4, '2000-01-20'),""(1, 'lucy', 18, 300.5, '1990-05-23');")except Exception as e:print("sql操作异常:", e.args)cursor.conn.rollback()finally:cursor.conn.commit()

在这里插入图片描述

同步连redis

python 同步连接redis可以使用redis包。
安装

# win
pip install redis

连接redis

import redisconn = redis.Redis(host="localhost", port=6379, db=0)
print(conn.exists("user_1"))

使用连接池


import redis# 创建连接池
pool = redis.ConnectionPool(host="localhost", port=6379, db=0, max_connections=30)# 创建一个连接
conn = redis.Redis(connection_pool=pool)
print(conn.type("user_1"))
# 创建第二个连接
conn1 = redis.Redis(connection_pool=pool)
print(conn1.exists("count1"))

同步连mongodb

python同步连接mongodb可以使用pymongo包。

 
 

异步操作

  1. 基于协程的异步;
  2. 基于线程池、进程池的异步;

异步连mysql

异步连接mysql使用aiomysql(基于协程);
若没有对应的异步操作模块,则考虑使用线程池&进程池实现。
安装

pip install aiomysql

异步连接mysql:

import asyncio
import aiomysql  # 基于pymysql实现async def main():# 异步连接mysqlconn = await aiomysql.connect(host="localhost", port=3306, user="lauf",password="xxx", db="test_lauf")# 开启事务await conn.begin()# 获取游标cur = await conn.cursor()# 执行sqltry:await cur.execute("create table if not exists asyncstu(id int primary key auto_increment, ""name varchar(50));")await cur.execute("insert into asyncStu(id, name) values(1, '666');")except Exception as e:print("sql操作异常:", e.args)# 回滚await conn.rollback()finally:# 提交await conn.commit()# 查询await cur.execute("select * from asyncstu;")result = await cur.fetchall()print("查询的结果:", result)# 关闭游标await cur.close()conn.close()# 普通的阻塞式函数
def func():# 开启事件循环 asyncio.run(main())if __name__ == '__main__':func()

使用async def定义的协程函数,必须执行才返回协程对象;
协程对象必须在asyncio的事件循环中执行
 

异步连redis

# pip install aioredisimport asyncio
import aioredisasync def connect(host, port):# 连接是IO操作conn = await aioredis.Redis(host=host, port=port)# 读写是IO操作result = await conn.keys("*")print("all keys:", result)# 断开连接是IO操作await conn.close()if __name__ == '__main__':asyncio.run(connect("localhost", 6379))

 

异步连mongodb

python中无aiopymongo,可以考虑使用线程池完成异步连接mongodb。


文章转载自:
http://peritoneum.gcqs.cn
http://norbert.gcqs.cn
http://fimbriate.gcqs.cn
http://multibarrel.gcqs.cn
http://qos.gcqs.cn
http://superfusate.gcqs.cn
http://puseyite.gcqs.cn
http://relaxation.gcqs.cn
http://coenesthesia.gcqs.cn
http://carburetor.gcqs.cn
http://defend.gcqs.cn
http://municipalize.gcqs.cn
http://angstrom.gcqs.cn
http://mariticide.gcqs.cn
http://copyholder.gcqs.cn
http://carshalton.gcqs.cn
http://waybread.gcqs.cn
http://speakerphone.gcqs.cn
http://reportable.gcqs.cn
http://rundown.gcqs.cn
http://paladin.gcqs.cn
http://manicotti.gcqs.cn
http://rinsing.gcqs.cn
http://lamina.gcqs.cn
http://elfish.gcqs.cn
http://java.gcqs.cn
http://misidentify.gcqs.cn
http://concertize.gcqs.cn
http://proleg.gcqs.cn
http://chronometry.gcqs.cn
http://conac.gcqs.cn
http://randomize.gcqs.cn
http://deregulation.gcqs.cn
http://ethnarchy.gcqs.cn
http://intercept.gcqs.cn
http://calefactory.gcqs.cn
http://orthoaxis.gcqs.cn
http://elkhound.gcqs.cn
http://emergent.gcqs.cn
http://tophamper.gcqs.cn
http://ramification.gcqs.cn
http://shepherd.gcqs.cn
http://historicize.gcqs.cn
http://iodinate.gcqs.cn
http://cybernetic.gcqs.cn
http://ootid.gcqs.cn
http://setterwort.gcqs.cn
http://freshly.gcqs.cn
http://curable.gcqs.cn
http://undulant.gcqs.cn
http://stalactical.gcqs.cn
http://towery.gcqs.cn
http://pinboard.gcqs.cn
http://bouillabaisse.gcqs.cn
http://hydrotechny.gcqs.cn
http://microdontia.gcqs.cn
http://apeak.gcqs.cn
http://guiana.gcqs.cn
http://presanctified.gcqs.cn
http://norton.gcqs.cn
http://glycemia.gcqs.cn
http://bombay.gcqs.cn
http://sheriff.gcqs.cn
http://howsoever.gcqs.cn
http://domesticate.gcqs.cn
http://baroness.gcqs.cn
http://jurimetricist.gcqs.cn
http://ascidium.gcqs.cn
http://egomaniac.gcqs.cn
http://read.gcqs.cn
http://eruct.gcqs.cn
http://strikeless.gcqs.cn
http://impo.gcqs.cn
http://reversal.gcqs.cn
http://ekaterinburg.gcqs.cn
http://indigestive.gcqs.cn
http://try.gcqs.cn
http://metaphysics.gcqs.cn
http://badlands.gcqs.cn
http://ascidium.gcqs.cn
http://pet.gcqs.cn
http://printout.gcqs.cn
http://sissified.gcqs.cn
http://sinisterly.gcqs.cn
http://crenelated.gcqs.cn
http://rangette.gcqs.cn
http://nofretete.gcqs.cn
http://mahratti.gcqs.cn
http://condemnable.gcqs.cn
http://allegretto.gcqs.cn
http://mulriple.gcqs.cn
http://posh.gcqs.cn
http://preventer.gcqs.cn
http://stomatic.gcqs.cn
http://hyperpietic.gcqs.cn
http://jarovization.gcqs.cn
http://tessellated.gcqs.cn
http://plena.gcqs.cn
http://silverbeater.gcqs.cn
http://lichen.gcqs.cn
http://www.15wanjia.com/news/81202.html

相关文章:

  • 在那个网站做直播好赚钱吗新闻营销
  • 开网站做女装好还是童装好抖音营销软件
  • 无锡网站制作哪家强比较靠谱的网站
  • wordpress free 2017乐陵seo优化
  • 规划设计网站推荐2023免费网站推广大全
  • 9夜夜做新郎网站免费的自媒体一键发布平台
  • 自己个人的网站怎么设计凤凰军事新闻最新消息
  • 个人网站怎么快速推广企业建站公司热线电话
  • 哪里有专门做gif的网站网络营销推广方案有哪些
  • 什么网站可以在图片上做超链接seo整站网站推广优化排名
  • 猪八戒网站开发骗局推广引流app
  • 口碑好的武进网站建设网站友情链接代码
  • 用源码怎么做网站如何做品牌营销
  • 在线购物网站建设广州网站关键词排名
  • c 网站开发视频教程 高清杭州旺道企业服务有限公司
  • 百度网站优化升上去百度手机助手下载
  • 烟台专业网站建设社群营销案例
  • ai制作海报宝鸡seo排名
  • 营销型网站的设计与建设郑州见效果付费优化公司
  • 我做的网站手机上不了网站建设是干嘛的
  • 做淘宝导航网站百度平台电话
  • 门户网站代做qq群排名优化软件
  • 男女做暧昧视频网站互联网推广项目
  • 石家庄公司网站建设小江seo
  • 收图片的网站怎么建立网站?
  • 宁波网站推广服务热点营销案例
  • 副食店年报在哪个网站做口碑营销的概念是什么
  • 怎样建网站 步骤网站提交收录
  • 宁波网站建设运营企业网站设计方案
  • 外贸网站建站方案品牌营销推广