使用python MySQLdb执行* .sql文件 [英] execute *.sql file with python MySQLdb

查看:275
本文介绍了使用python MySQLdb执行* .sql文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用MySQLdb python驱动程序执行* .sql文件中存储的sql脚本.我在尝试

How can execute sql script stored in *.sql file using MySQLdb python driver. I was trying



cursor.execute(file(PATH_TO_FILE).read())

但这不起作用,因为 cursor.execute 一次只能运行一个sql命令.我的sql脚本包含多个sql语句.我也在尝试

but this doesn't work because cursor.execute can run only one sql command at once. My sql script contains several sql statements instead. Also I was trying


cursor.execute('source %s'%PATH_TO_FILE)

但也没有成功.

推荐答案

for line in open(PATH_TO_FILE):
    cursor.execute(line)

这假设您的文件中每行有一条SQL语句.否则,您需要编写一些规则以将行连接在一起.

This assumes you have one SQL statement per line in your file. Otherwise you'll need to write some rules to join lines together.

这篇关于使用python MySQLdb执行* .sql文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆