from twisted.enterprise import adbapi from twisted.internet import reactor def creat_conn(): # 数据库基本配置 db_settings = dict(db='testdb', host='localhost', port = 3306,user = 'root',passwd = 'pwd', charset='utf8') db_conn = adbapi.ConnectionPool('MySQLdb', **db_settings) return db_conn def go_insert(cursor, sql): # 对数据库进行插入操作,并不需要commit,twisted会自动commit try: with open('info_person.csv','r') as f: for line in f: values=tuple([s.strip() for s in line.split(',')]) cursor.execute(sql,values) except Exception as e: print(e) def handle_error(failure): # 打印错误 if failure: print(failure) def main(): db_conn = creat_conn() insert_sql ='INSERT INTO testdb.test(c1,c2,c3,c4) VALUES (%s,%s,%s,%s)' query = db_conn.runInteraction(go_insert, insert_sql) query.addCallbacks(handle_error) reactor.callLater(4, reactor.stop) reactor.run() if __name__ == '__main__': main()