python如何通过twisted实现数据库异步插入

发布时间:2020-10-05 10:07:38 作者:北门吹雪
来源:脚本之家 阅读:165

如何通过twisted实现数据库异步插入?

  1. 导入adbapi

  2. 生成数据库连接池

  3. 执行数据数据库插入操作

  4. 打印错误信息,并排错

#!/usr/bin/python3
 
__author__ = 'beimenchuixue'
__blog__ = 'http://www.cnblogs.com/2bjiujiu/'
 
import pymysql
from twisted.enterprise import adbapi
from twisted.internet import reactor
 
 
def go_insert(cursor, sql):
  # 对数据库进行插入操作,并不需要commit,twisted会自动帮我commit
  try:
    for i in range(10):
      data = str(i)
      cursor.execute(sql, data)
  except Exception as e:
    print(e)
 
 
def handle_error(failure):
  # 打印错误
  if failure:
    print(failure)
 
 
if __name__ == '__main__':
  # 数据库基本配置
  db_settings = {
    'host': 'localhost',
    'db': 'jobole',
    'user': 'root',
    'password': 'passwort',
    'charset': 'utf8',
    'use_unicode': True
  }
  # sql语句模版
  insert_sql = 'insert into test_1(text_1) value(%s)'
   
  # 普通方法插入数据
  # conn = pymysql.connect(**db_settings)
  # cursor = conn.cursor()
  # cursor.execute(insert_sql, '1')
  # conn.commit()
   
  try:
    # 生成连接池
    db_conn = adbapi.ConnectionPool('pymysql', **db_settings)
    # 通过连接池执行具体的sql操作,返回一个对象
    query = db_conn.runInteraction(go_insert, insert_sql)
    # 对错误信息进行提示处理
    query.addCallbacks(handle_error)
  except Exception as e:
    print(e)
   
  # 定时,给4秒时间让twisted异步框架完成数据库插入异步操作,没有定时什么都不会做
  reactor.callLater(4, reactor.stop)
  reactor.run()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. Python通过Thrift插入Hbase实验
  2. python 插入mysql数据库数据

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python twisted 数据库

上一篇:python3发送邮件需要经过代理服务器的示例代码

下一篇:深入浅析nuxt.js基于ssh的vue通用框架

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》