1

我想在 mysql 中为我的应用程序创建数据库结构,我有大约 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

但是它们同时运行,并且我在下表中有外键,因此它给出了错误。

4

2 回答 2

0

我写了一个 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 文件,您可能需要 split(";") 来提取每个查询并cursor.execute(sql)为每个查询调用。随意编辑此答案以纳入这些改进。

于 2013-10-07T21:13:34.597 回答
0

脚本没有同时运行。mysql客户端不以多线程方式执行。

但是,您可能会按照导致外键引用您尚未定义的表的顺序来采购脚本,这是一个问题。

对于此问题,您有两种可能的修复方法:

  • 按顺序创建表以避免此问题。

  • 创建没有外键的所有表,然后运行另一个包含ALTER TABLE ADD FOREIGN KEY... 语句的脚本。

于 2013-10-07T21:23:57.767 回答