Python类内调用get_value报NameError未定义 关联SQLite从TXT导入数据
报错原因与修复方案
核心问题点
- 类方法调用逻辑错误:Python中类的实例方法必须将
self作为第一个参数,你定义的get_value、insert_data都未添加该参数;且在insert_data中直接写get_value(item)调用,会被识别为查找全局作用域的同名函数,找不到就触发NameError。 get_value方法缺少入参:该方法内部使用了item变量,但方法定义时未声明接收item参数,即使修正调用方式也会触发变量未定义报错。- 隐藏的运行时错误:
INSERT语句占位符数量不匹配:声明了4个插入字段,但只写了3个?占位符,执行时会报参数数量与占位符不符的错误。- 数据遍历逻辑缺陷:当前代码只会保留最后一组日志数据,不会在两组数据的空行处触发插入操作,前面的分组数据会被后续遍历的结果覆盖。
修复后代码
import sqlite3 class InputFromIPLog: def __init__(self, db_conn): # 传入数据库连接,避免硬依赖全局游标变量 self.cursor = db_conn.cursor() def get_value(self, item): info = item.strip().split(':') val = info[1].strip().split(',') return val[0].strip() def insert_data(self): with open("new_iplog.txt", "r") as f: file_data = f.readlines() # 初始化单组数据的存储变量 input_gamertag = "" input_ip_address = "" input_xuid = "" input_mid = "" for item in file_data: # 遇到空行代表上一组数据采集完成,触发插入 if item.strip() == "": # 跳过无有效内容的空行 if not input_gamertag: continue # 修正占位符为4个,与字段数量匹配 self.cursor.execute( "INSERT INTO userinfo (gamertag, ip, xuid, mid) values(?, ?, ?, ?)", (input_gamertag, input_ip_address, input_xuid, input_mid) ) # 重置变量,准备采集下一组数据 input_gamertag = "" input_ip_address = "" input_xuid = "" input_mid = "" continue if "Gamertag" in item: input_gamertag = self.get_value(item) elif "IP Address" in item: input_ip_address = self.get_value(item) elif 'XUID' in item: input_xuid = self.get_value(item) elif 'MID' in item: input_mid = self.get_value(item) # 处理文件末尾无空行结尾的最后一组数据 if input_gamertag: self.cursor.execute( "INSERT INTO userinfo (gamertag, ip, xuid, mid) values(?, ?, ?, ?)", (input_gamertag, input_ip_address, input_xuid, input_mid) )
调用示例
# 初始化数据库连接后传入类实例 conn = sqlite3.connect("iplog.db") processor = InputFromIPLog(conn) processor.insert_data() # 提交事务,确保数据写入 conn.commit() conn.close()
内容的提问来源于stack exchange,提问作者Brian
相关产品推荐
相关产品推荐

