作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 StackOverflow 上看到过一些类似的问题,但没有找到有效的答案;见http://stackoverflow.com/questions/4408714/execute-sql-file-with-python-mysqldb和 http://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/
我是一名优秀的程序员,十分优秀!