Python 3.4.3、MariaDB 10.0.21、MariaDB ODBC 连接器 1.0.0、pypyodbc 1.3.3,在 64 位 Windows 7 上均为 64 位。
我有一个 python 脚本,它应该创建一个表,用固定宽度文件中的数据填充它,然后对它运行一个 SELECT 语句。都是简单的东西。我的脚本看起来像这样:
import pypyodbc
def do_stuff(name, password, filepath):
db = pypyodbc.connect(driver = "{MariaDB ODBC 1.0 Driver}",
server = "localhost", uid = name,
pwd = password, autocommit = True)
cursor = db.cursor()
cursor.execute("CREATE TABLE `foo`.`bar` (`col1` INT);")
cursor.execute("LOAD DATA LOCAL INFILE '%s' INTO TABLE `foo`.`bar` (@row) SET col1 = SUBSTR(@row,1,1)" % filepath.replace("\\", "\\\\"))
for row in cursor.execute("SELECT * FROM `foo`.`bar`"):
print(row)
db.close()
do_stuff("root", "password", r"C:\\Users\\laj\\Desktop\\test.txt")
它从文本文件中的每一行中获取第一个字符并将其粘贴在表中的唯一列中。但是,当“SELECT”语句出现时,我遇到以下错误:
Traceback (most recent call last):
File "test.py", line 25, in <module>
do_stuff("root", "oag123", r"C:\\Users\\laj\\Desktop\\test.txt")
File "test.py", line 21, in do_stuff
for row in cursor.execute("SELECT * FROM `foo`.`bar`"):
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 1605, in execute
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 1631, in execdirect
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 986, in check_success
File "C:\Python34\lib\site-packages\pypyodbc-1.3.3-py3.4.egg\pypyodbc.py", line 964, in ctrl_err
pypyodbc.Error: ('HY000', '[HY000] Unknown prepared statement handler (5) given to mysqld_stmt_reset')
真正让我感动的是,我可以通过在填充表和执行“SELECT”之间关闭并重新打开数据库连接来摆脱错误,如下所示:
import pypyodbc
def do_stuff(name, password, filepath):
db = pypyodbc.connect(driver = "{MariaDB ODBC 1.0 Driver}",
server = "localhost", uid = name,
pwd = password, autocommit = True)
cursor = db.cursor()
cursor.execute("CREATE TABLE `foo`.`bar` (`col1` INT);")
cursor.execute("LOAD DATA LOCAL INFILE '%s' INTO TABLE `foo`.`bar` (@row) SET col1 = SUBSTR(@row,1,1)" % filepath.replace("\\", "\\\\"))
db.close()
db = pypyodbc.connect(driver = "{MariaDB ODBC 1.0 Driver}",
server = "localhost", uid = name,
pwd = password, autocommit = True)
cursor = db.cursor()
for row in cursor.execute("SELECT * FROM `foo`.`bar`"):
print(row)
db.close()
do_stuff("root", "password", r"C:\\Users\\laj\\Desktop\\test.txt")
不幸的是,这实际上不是我的问题的有效解决方案。这不仅是我不应该做的事情,而且对于临时表也无济于事,因为它们只是在“修复”的断开连接阶段被丢弃。任何见解都会很棒,这让我陷入困境。