beishanfengyun
2017-11-08 11:46
采纳率: 42.9%
浏览 5.6k

Python 使用多线程写入数据库,报错

#问题描述,定义了一个函数,用于数据库写入表,直接使用函数是可以运行,但我创建了一个
多线程,在多线程里面使用运行函数,然后后错
import mysql.connector
from mysql.connector import errorcode
import threading,time

#数据库连接参数

def sqlconn():
dbconfig={'user': 'qrcodeadmin','password': 'careyes!@#','host': '119.23.8.62','port':3308,'database': 'qrcodes','raise_on_warnings': True}
try:
cnx = mysql.connector.connect(**dbconfig)
print('数据库连接成功')
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err.encode)
return cnx

def handle():
while(True):
global UID,ID
for i in range(50):
print(i)
sqlinsert="INSERT INTO qrcode (URL,QrID) VALUES (%s,%s)",(UID,ID)
cur.execute(sqlinsert[0],sqlinsert[1])
cur.execute(sqlinsert[0],sqlinsert[1])
dbcon.commit()

if name=='__main__':
global cur
dbcon=sqlconn()
cur=dbcon.cursor()
UID=' MjAxNzEwMTExMjQyNDQ'
ID='201710111242420111'
#直接使用handle可以运行
handle()
#-------------
sql_thread=threading.Thread(target=handle)
#如果使用线程就会报错
sql_thread.start()
dbcon.close()
print(dbcon)

    #报错内容
    Exception in thread Thread-1:

Traceback (most recent call last):
File "C:\Python\lib\site-packages\mysql\connector\connection.py", line 280, in
_send_cmd
self._socket.send(
AttributeError: 'NoneType' object has no attribute 'send'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Python\lib\threading.py", line 914, in _bootstrap_inner
self.run()
File "C:\Python\lib\threading.py", line 862, in run
self._target(*self._args, **self._kwargs)
File "sqltestV0.2_Thread.py", line 34, in handle
cur.execute(sqlinsert[0],sqlinsert[1])
File "C:\Python\lib\site-packages\mysql\connector\cursor.py", line 561, in exe
cute
self._handle_result(self._connection.cmd_query(stmt))
File "C:\Python\lib\site-packages\mysql\connector\connection.py", line 514, in
cmd_query
result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
File "C:\Python\lib\site-packages\mysql\connector\connection.py", line 284, in
_send_cmd
raise errors.OperationalError("MySQL Connection not available.")
mysql.connector.errors.OperationalError: MySQL Connection not available.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

5条回答 默认 最新

相关推荐 更多相似问题