0

当我尝试在我的 process_id 函数中使用或创建一个 db 游标时,我遇到了线程错误。每个线程都必须使用数据库来处理它们传递的 id 的数据。

我根本无法在 thread/process_id 中使用游标(我得到线程错误并且数据库永远不会更新)......我已经用很多不同的方式对其进行了编码。当我不使用线程时,该代码有效。

我对如何编写这段代码有非常具体的要求,缓慢而稳定就可以了。在发布之前,我还删除了很多错误处理/日志记录。需要守护程序/无限循环。

如何在每个线程中启动一个新光标?

import threading
import time
from datetime import datetime
import os
import jaydebeapi, sys

#Enter the values for you database connection
database = "REMOVED"          
hostname = "REMOVED"
port = "REMOVED"               
uid = "REMOVED"       
pwd = "REMOVED" 

connection_string='jdbc:db2://'+hostname+':'+port+'/'+database

if (sys.version_info >= (3,0)):
    conn = jaydebeapi.connect("com.ibm.db2.jcc.DB2Driver", connection_string, [uid, pwd], jars="REMOVED")
else:
    conn = jaydebeapi.connect("com.ibm.db2.jcc.DB2Driver", [connection_string, uid, pwd])

# Thread Pool Variables
max_threads = 5
used_threads = 0

# define main cursor
cus=conn.cursor()

def process_id(id):
    #create a cursor for a thread
    cus_id=conn.cursor()
    cus_id.execute("SOME QUERY;")
    cus_id.close()
    global used_threads
    used_threads = used_threads - 1         
    return 0

def daemon():
    global num_threads, used_threads
    print("Daemon running...")
    while True:
        #ids to process are loaded into a list...
        for id in ids_to_process:
            if used_threads < max_threads:
                t = threading.Thread(target=process_id, args=(int(id),))
                t.start()
                used_threads += 1
    return 0

daemon()
4

0 回答 0