我想在mysql中为我的应用程序创建DB结构,我有大约100个脚本,它们将在不同的模式中创建表、sp和函数。
请建议我如何运行脚本,一个接一个,如何停止,如果以前的脚本失败。我使用的是MySQL 5.6版本。
我正在使用文本文件运行它们。
mysql> source /mypath/CreateDB.sql
其中包含
tee /logout/session.txt
source /mypath/00-CreateSchema.sql
source /mypath/01-CreateTable1.sql
source /mypath/01-CreateTable2.sql
source /mypath/01-CreateTable3.sql
但是它们同时运行,我在下面的表中有外键,因为它出现了错误。
发布于 2013-10-07 21:23:57
脚本不是同时运行的。mysql客户端不以多线程方式执行。
但是,您可能是按照导致外键指向尚未定义的引用表的顺序来获取脚本的,这是一个问题。
对于这个问题,您有两个可能的解决方法:
ALTER TABLE ADD FOREIGN KEY的脚本.语句。发布于 2013-10-07 21:13:34
我编写了一个Python函数来执行SQL文件:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Download it at http://sourceforge.net/projects/mysql-python/?source=dlp
# Tutorials: http://mysql-python.sourceforge.net/MySQLdb.html
# http://zetcode.com/db/mysqlpython/
import MySQLdb as mdb
import datetime, time
def run_sql_file(filename, connection):
'''
The function takes a filename and a connection as input
and will run the SQL query on the given connection
'''
start = time.time()
file = open(filename, 'r')
sql = s = " ".join(file.readlines())
print "Start executing: " + filename + " at " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M")) + "\n" + sql
cursor = connection.cursor()
cursor.execute(sql)
connection.commit()
end = time.time()
print "Time elapsed to run the query:"
print str((end - start)*1000) + ' ms'
def main():
connection = mdb.connect('127.0.0.1', 'root', 'password', 'database_name')
run_sql_file("my_query_file.sql", connection)
connection.close()
if __name__ == "__main__":
main()我还没有在存储过程或大型SQL语句中尝试过这种方法。另外,如果您有包含多个SQL查询的SQL文件,则可能需要拆分(“;”)来提取每个查询并为每个查询调用cursor.execute(sql)。请随意编辑这个答案,以纳入这些改进。
https://stackoverflow.com/questions/19220122
复制相似问题