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

yipeiwu_com6年前Python基础

如何通过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()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用Python编写Prometheus监控的方法

要使用python编写Prometheus监控,需要你先开启Prometheus集群。可以参考/post/148895.htm 安装。在python中实现服务器端。在Prometheus...

python中的插值 scipy-interp的实现代码

python中的插值 scipy-interp的实现代码

具体代码如下所示: import numpy as np from matplotlib import pyplot as plt from scipy.interpolate im...

Python函数定义及传参方式详解(4种)

一、函数初识 1、定义:将一组语句的集合通过一个名字(函数名)封装起来,要想执行这个函数,只需调用其函数名即可。  2、好处:代码重用;保持一致性;可扩展性。 3、示例如下:    ...

如何利用Python开发一个简单的猜数字游戏

如何利用Python开发一个简单的猜数字游戏

前言 本文介绍如何使用Python制作一个简单的猜数字游戏。 游戏规则 玩家将猜测一个数字。如果猜测是正确的,玩家赢。如果不正确,程序会提示玩家所猜的数字与实际数字相比是“大(high)...

NumPy 如何生成多维数组的方法

Python现在是最热门的人工智能语言,各种工具的支持如Google的Tensorflow,都是首选支持Python的。 但是,与R语言不同,Python语言设计时,并没有考虑对于矩阵...