gpt4 book ai didi

python - 如何在 Python 脚本中导入 MySQL 数据库?

转载 作者:行者123 更新时间:2023-11-29 01:53:55 24 4
gpt4 key购买 nike

我在 StackOverflow 上看到过一些类似的问题,但没有找到有效的答案;见http://stackoverflow.com/questions/4408714/execute-sql-file-with-python-mysqldbhttp://stackoverflow.com/questions/10593876/execute-sql-file-in-python-with-mysqldb?lq=1

这是我的代码:

import pymysql
import sys
import access # holds credentials
import mysql_connector # connects to MySQL, is fully functional


class CreateDB(object):
def __init__(self):
self.cursor = None
self.conn = pymysql.connect(host, user, passwd)

def create_database(self):
try:
with self.conn.cursor() as cursor:
for line in open('file.sql'):
cursor.execute(line)
self.conn.commit()

except Warning as warn:
f = open(access.Credentials().error_log, 'a')
f.write('Warning: %s ' % warn + '\nStop.\n')
sys.exit()

create = CreateDB()
create.create_database()

当我运行我的脚本时,出现以下错误:

pymysql.err.InternalError: (1065, 'Query was empty')

当我直接通过 MySQL 导入时,我的 .sql 文件成功加载,文件的每一行都有一个查询。有人对此有解决方案吗?我遵循了其他帖子的建议,但没有取得任何成功。

最佳答案

通过以下方式处理文件末尾的空行:

如果 line.strip(): cursor.execute(line)

关于python - 如何在 Python 脚本中导入 MySQL 数据库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34275794/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com