如何使用MySQLdb python驱动程序执行存储在* .sql文件中的sql脚本。我在努力
cursor.execute(file(PATH_TO_FILE).read())
但这不起作用,因为cursor.execute一次只能运行一个sql命令。我的sql脚本包含几个sql语句。我也在努力
cursor.execute('source %s'%PATH_TO_FILE)
但也没有成功。
for line in open(PATH_TO_FILE):
cursor.execute(line)
这假设您的文件中每行有一个SQL语句。否则,您需要编写一些规则来将线连接在一起。
这是一个代码片段,它将导入来自导出的典型.sql
。 (我成功地使用了Sequel Pro的出口。)处理多行查询和评论(#
)。
import MySQLdb
from configdb import DB_HOST, DB_PASS, DB_USER, DB_DATABASE_NAME
db = MySQLdb.connect(host=DB_HOST, # your host, usually localhost
user=DB_USER, # your username
passwd=DB_PASS, # your password
db=DB_DATABASE_NAME) # name of the data base
cur = db.cursor()
PATH_TO_FILE = "db-testcases.sql"
fullLine = ''
for line in open(PATH_TO_FILE):
tempLine = line.strip()
# Skip empty lines.
# However, it seems "strip" doesn't remove every sort of whitespace.
# So, we also catch the "Query was empty" error below.
if len(tempLine) == 0:
continue
# Skip comments
if tempLine[0] == '#':
continue
fullLine += line
if not ';' in line:
continue
# You can remove this. It's for debugging purposes.
print "[line] ", fullLine, "[/line]"
try:
cur.execute(fullLine)
except MySQLdb.OperationalError as e:
if e[1] == 'Query was empty':
continue
raise e
fullLine = ''
db.close()
您是否可以使用其他数据库驱动程序? 如果是:你想要的是MySQL的MySQL Connector/Python驱动程序。
它的cursor.execute
method支持通过传递Multi=True
一次执行多个SQL语句。
不需要用分号拆分文件中的SQL语句。
简单的例子(主要是从第二个链接复制和粘贴,我刚刚添加了从文件中读取SQL):
import mysql.connector
file = open('test.sql')
sql = file.read()
cnx = mysql.connector.connect(user='uuu', password='ppp', host='hhh', database='ddd')
cursor = cnx.cursor()
for result in cursor.execute(sql, multi=True):
if result.with_rows:
print("Rows produced by statement '{}':".format(
result.statement))
print(result.fetchall())
else:
print("Number of rows affected by statement '{}': {}".format(
result.statement, result.rowcount))
cnx.close()
我正在使用它来导入MySQL转储(在phpMyAdmin中创建,将整个数据库导出到SQL文件)从* .sql文件返回到数据库。
如何使用pexpect library?这个想法是,你可以启动一个进程pexpect.spawn(...)
,并等到该进程的输出包含某个模式process.expect(pattern)
。
我实际上用它连接到mysql客户端并执行一些sql脚本。
连接:
import pexpect
process = pexpect.spawn("mysql", ["-u", user, "-p"])
process.expect("Enter password")
process.sendline(password)
process.expect("mysql>")
这样,密码不会硬编码到命令行参数中(消除安全风险)。
执行甚至几个sql脚本:
error = False
for script in sql_scripts:
process.sendline("source {};".format(script))
index = process.expect(["mysql>", "ERROR"])
# Error occurred, interrupt
if index == 1:
error = True
break
if not error:
# commit changes of the scripts
process.sendline("COMMIT;")
process.expect("mysql>")
print "Everything fine"
else:
# don't commit + print error message
print "Your scripts have errors"
请注意,您始终调用expect(pattern)
,并且它匹配,否则您将收到超时错误。我需要这段代码来执行几个sql脚本,并且只在没有错误发生的情况下提交它们的更改,但它很容易适用于只有一个脚本的用例。
从python,我启动一个mysql进程来为我执行该文件:
from subprocess import Popen, PIPE
process = Popen(['mysql', db, '-u', user, '-p', passwd],
stdout=PIPE, stdin=PIPE)
output = process.communicate('source ' + filename)[0]
我还需要执行一个SQL文件,但问题是每行没有一个语句,所以接受的答案对我不起作用。
我想要执行的SQL文件如下所示:
-- SQL script to bootstrap the DB:
--
CREATE USER 'x'@'%' IDENTIFIED BY 'x';
GRANT ALL PRIVILEGES ON mystore.* TO 'x'@'%';
GRANT ALL ON `%`.* TO 'x'@`%`;
FLUSH PRIVILEGES;
--
--
CREATE DATABASE oozie;
GRANT ALL PRIVILEGES ON oozie.* TO 'oozie'@'localhost' IDENTIFIED BY 'oozie';
GRANT ALL PRIVILEGES ON oozie.* TO 'oozie'@'%' IDENTIFIED BY 'oozie';
FLUSH PRIVILEGES;
--
USE oozie;
--
CREATE TABLE `BUNDLE_ACTIONS` (
`bundle_action_id` varchar(255) NOT NULL,
`bundle_id` varchar(255) DEFAULT NULL,
`coord_id` varchar(255) DEFAULT NULL,
`coord_name` varchar(255) DEFAULT NULL,
`critical` int(11) DEFAULT NULL,
`last_modified_time` datetime DEFAULT NULL,
`pending` int(11) DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
`bean_type` varchar(31) DEFAULT NULL,
PRIMARY KEY (`bundle_action_id`),
KEY `I_BNDLTNS_DTYPE` (`bean_type`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
--
上面文件中的一些语句位于一行,一些语句也跨越多行(如末尾的CREATE TABLE)。还有一些SQL内联注释行以“ - ”开头。
正如ThomasK所建议的那样,我必须编写一些简单的规则来将行连接到一个语句中。我最终得到了一个执行sql文件的函数:
def exec_sql_file(cursor, sql_file):
print "\n[INFO] Executing SQL script file: '%s'" % (sql_file)
statement = ""
for line in open(sql_file):
if re.match(r'--', line): # ignore sql comment lines
continue
if not re.search(r';$', line): # keep appending lines that don't end in ';'
statement = statement + line
else: # when you get a line ending in ';' then exec statement and reset for next statement
statement = statement + line
#print "\n\n[DEBUG] Executing SQL statement:\n%s" % (statement)
try:
cursor.execute(statement)
except (OperationalError, ProgrammingError) as e:
print "\n[WARN] MySQLError during execute statement \n\tArgs: '%s'" % (str(e.args))
statement = ""
我确信还有改进的余地,但是现在它对我来说效果很好。希望有人发现它有用。
至少MySQLdb
1.2.3似乎允许开箱即用,你只需要调用cursor.nextset()
循环返回结果集。
db = conn.cursor()
db.execute('SELECT 1; SELECT 2;')
more = True
while more:
print db.fetchall()
more = db.nextset()
如果您想完全确定已启用对此的支持,和/或禁用支持,您可以使用以下内容:
MYSQL_OPTION_MULTI_STATEMENTS_ON = 0
MYSQL_OPTION_MULTI_STATEMENTS_OFF = 1
conn.set_server_option(MYSQL_OPTION_MULTI_STATEMENTS_ON)
# Multiple statement execution here...
conn.set_server_option(MYSQL_OPTION_MULTI_STATEMENTS_OFF)
这对我有用:
with open('schema.sql') as f:
cursor.execute(f.read().decode('utf-8'), multi=True)
允许在没有任何解析的情况下利用MySQL解释器的另一个解决方案是使用os.system
命令直接在python中运行MySQL提示命令:
from os import system
USERNAME = "root"
PASSWORD = "root"
DBNAME = "pablo"
HOST = "localhost"
PORT = 3306
FILE = "file.sql"
command = """mysql -u %s -p"%s" --host %s --port %s %s < %s""" %(USERNAME, PASSWORD, HOST, PORT, DBNAME, FILE)
system(command)
它可以避免任何解析错误,例如你有一个带有笑脸;-)
的字符串变量,或者你检查;
作为最后一个字符,如果你之后有评论像SELECT * FROM foo_table; # selecting data
这里的许多答案都有严重的缺陷......
首先不要尝试自己解析开放式的sql脚本!如果你认为这很容易做到,你就不会知道sql有多强大和复杂。严重的SQL脚本肯定涉及跨越多行的语句和过程定义。在脚本中间显式声明和更改分隔符也很常见。您还可以在彼此之间嵌套源命令。出于这么多原因,您希望通过MySQL客户端运行脚本并允许它处理繁重的工作。试图重新发明这是一个充满危险和巨大浪费时间的事情。也许如果你是唯一一个编写这些脚本的人,并且你没有写任何复杂的东西,你可以侥幸逃脱,但为什么要限制自己到这样的程度?机器生成的脚本或其他开发人员编写的脚本怎么样?
@jdferreira的答案是正确的,但也有问题和缺点。最重要的是通过以这种方式将连接参数发送到进程来打开安全漏洞。
这是您的复制和粘贴乐趣的解决方案/示例。我的扩展讨论如下:
首先,创建一个单独的配置文件以保存您的用户名和密码。
DB-creds.cfg
[client]
user = XXXXXXX
password = YYYYYYY
对该文件系统权限执行权限,因此python进程可以从中读取,但没有人可以查看谁不应该。
然后,使用这个Python(在我的示例中,creds文件与py脚本相邻):
#!/usr/bin/python
import os
import sys
import MySQLdb
from subprocess import Popen, PIPE, STDOUT
__MYSQL_CLIENT_PATH = "mysql"
__THIS_DIR = os.path.dirname( os.path.realpath( sys.argv[0] ) )
__DB_CONFIG_PATH = os.path.join( __THIS_DIR, "db-creds.cfg" )
__DB_CONFIG_SECTION = "client"
__DB_CONN_HOST = "localhost"
__DB_CONN_PORT = 3306
# ----------------------------------------------------------------
class MySqlScriptError( Exception ):
def __init__( self, dbName, scriptPath, stdOut, stdErr ):
Exception.__init__( self )
self.dbName = dbName
self.scriptPath = scriptPath
self.priorOutput = stdOut
self.errorMsg = stdErr
errNumParts = stdErr.split("(")
try : self.errorNum = long( errNumParts[0].replace("ERROR","").strip() )
except: self.errorNum = None
try : self.sqlState = long( errNumParts[1].split(")")[0].strip() )
except: self.sqlState = None
def __str__( self ):
return ("--- MySqlScriptError ---\n" +
"Script: %s\n" % (self.scriptPath,) +
"Database: %s\n" % (self.dbName,) +
self.errorMsg )
def __repr__( self ): return self.__str__()
# ----------------------------------------------------------------
def databaseLoginParms() :
from ConfigParser import RawConfigParser
parser = RawConfigParser()
parser.read( __DB_CONFIG_PATH )
return ( parser.get( __DB_CONFIG_SECTION, "user" ).strip(),
parser.get( __DB_CONFIG_SECTION, "password" ).strip() )
def databaseConn( username, password, dbName ):
return MySQLdb.connect( host=__DB_CONN_HOST, port=__DB_CONN_PORT,
user=username, passwd=password, db=dbName )
def executeSqlScript( dbName, scriptPath, ignoreErrors=False ) :
scriptDirPath = os.path.dirname( os.path.realpath( scriptPath ) )
sourceCmd = "SOURCE %s" % (scriptPath,)
cmdList = [ __MYSQL_CLIENT_PATH,
"--defaults-extra-file=%s" % (__DB_CONFIG_PATH,) ,
"--database", dbName,
"--unbuffered" ]
if ignoreErrors :
cmdList.append( "--force" )
else:
cmdList.extend( ["--execute", sourceCmd ] )
process = Popen( cmdList
, cwd=scriptDirPath
, stdout=PIPE
, stderr=(STDOUT if ignoreErrors else PIPE)
, stdin=(PIPE if ignoreErrors else None) )
stdOut, stdErr = process.communicate( sourceCmd if ignoreErrors else None )
if stdErr is not None and len(stdErr) > 0 :
raise MySqlScriptError( dbName, scriptPath, stdOut, stdErr )
return stdOut
如果你想测试它,添加:
if __name__ == "__main__":
( username, password ) = databaseLoginParms()
dbName = "ExampleDatabase"
print "MySQLdb Test"
print
conn = databaseConn( username, password, dbName )
cursor = conn.cursor()
cursor.execute( "show tables" )
print cursor.fetchall()
cursor.close()
conn.close()
print
print "-----------------"
print "Execute Script with ignore errors"
print
scriptPath = "test.sql"
print executeSqlScript( dbName, scriptPath,
ignoreErrors=True )
print
print "-----------------"
print "Execute Script WITHOUT ignore errors"
print
try : print executeSqlScript( dbName, scriptPath )
except MySqlScriptError as e :
print "dbName: %s" % (e.dbName,)
print "scriptPath: %s" % (e.scriptPath,)
print "errorNum: %s" % (str(e.errorNum),)
print "sqlState: %s" % (str(e.sqlState),)
print "priorOutput:"
print e.priorOutput
print
print "errorMsg:"
print e.errorMsg
print
print e
print
为了更好的衡量,这里有一个示例sql脚本来提供它:
TEST.SQL
show tables;
blow up;
show tables;
所以,现在进行一些讨论。
首先,我将说明如何使用MySQLdb以及此外部脚本执行,同时将信用卡存储在一个可用于两者的共享文件中。
通过在命令行上使用--defaults-extra-file
,您可以安全地传递连接参数。
--force
和stdin流式传输源命令的组合OR --execute
在外部运行命令让你决定脚本将如何运行。这是通过忽略错误并继续运行,或在错误发生时立即停止。
结果回归的顺序也将通过--unbuffered
保留。没有它,你的stdout和stderr流将在它们的顺序中混乱和未定义,这使得很难弄清楚在将它与输入sql进行比较时哪些有效,哪些无效。
使用Popen cwd=scriptDirPath
让你使用相对路径将源命令嵌套在另一个中。如果您的脚本都位于同一目录(或相对于它的已知路径)中,那么您可以引用相对于顶级脚本所在位置的脚本。
最后,我投入了一个异常类,其中包含了您可能想要发生的所有信息。如果您没有使用ignoreErrors选项,那么当出现错误并且脚本已停止运行该错误时,将在您的python中抛出其中一个异常。
当您的sql脚本包含空行并且您的查询语句跨越多行时,接受的答案将遇到问题。相反,使用以下方法将解决问题:
f = open(filename, 'r')
query = " ".join(f.readlines())
c.execute(query)
加载mysqldump文件:
for line in open(PATH_TO_FILE).read().split(';\n'):
cursor.execute(line)