代码之家  ›  专栏  ›  技术社区  ›  Nick Fortescue

将SQLite3迁移到MySQL的快速简单方法?[关闭]

  •  255
  • Nick Fortescue  · 技术社区  · 17 年前

    有人知道将SQLite3数据库迁移到MySQL的快速简单方法吗?

    17 回复  |  直到 2 年前
        1
  •  55
  •   David d C e Freitas    8 年前

    每个人似乎都从一些greps和perl表达式开始,你或多或少会得到一些适用于你特定数据集的东西,但你不知道它是否正确导入了数据。我非常惊讶没有人建立一个可以在两者之间转换的可靠库。

    这里列出了我所知道的两种文件格式之间SQL语法的所有差异: 以以下开头的行:

    • 事务开始
    • 承诺
    • sqlite_sequence
    • 索引

    MySQL中未使用

    • SQLite使用 CREATE TABLE/INSERT INTO "table_name" MySQL使用 CREATE TABLE/INSERT INTO table_name
    • MySQL在模式定义中不使用引号
    • MySQL对内部的字符串使用单引号 INSERT INTO 条款
    • SQLite和MySQL在内部转义字符串的方式不同 插入 条款
    • SQLite使用 't' 'f' 对于布尔值,MySQL使用 1 0 (当你的字典里有一个字符串,比如“I do,you don't”时,这个简单的正则表达式可能会失败 插入 )
    • SQLLite使用 AUTOINCREMENT MySQL使用 AUTO_INCREMENT

    这是一个非常基本的黑客攻击perl脚本,适用于 我的 数据集,并检查我在网上发现的其他perl脚本中的更多这些条件。Nu保证它将适用于您的数据,但请随时修改并发布回此处。

    #! /usr/bin/perl
    
    while ($line = <>){
        if (($line !~  /BEGIN TRANSACTION/) && ($line !~ /COMMIT/) && ($line !~ /sqlite_sequence/) && ($line !~ /CREATE UNIQUE INDEX/)){
            
            if ($line =~ /CREATE TABLE \"([a-z_]*)\"(.*)/i){
                $name = $1;
                $sub = $2;
                $sub =~ s/\"//g;
                $line = "DROP TABLE IF EXISTS $name;\nCREATE TABLE IF NOT EXISTS $name$sub\n";
            }
            elsif ($line =~ /INSERT INTO \"([a-z_]*)\"(.*)/i){
                $line = "INSERT INTO $1$2\n";
                $line =~ s/\"/\\\"/g;
                $line =~ s/\"/\'/g;
            }else{
                $line =~ s/\'\'/\\\'/g;
            }
            $line =~ s/([^\\'])\'t\'(.)/$1THIS_IS_TRUE$2/g;
            $line =~ s/THIS_IS_TRUE/1/g;
            $line =~ s/([^\\'])\'f\'(.)/$1THIS_IS_FALSE$2/g;
            $line =~ s/THIS_IS_FALSE/0/g;
            $line =~ s/AUTOINCREMENT/AUTO_INCREMENT/g;
            print $line;
        }
    }
    
        2
  •  99
  •   Shalmanese    16 年前

    以下是转换器列表(自2011年以来未更新):


    另一种效果很好但很少被提及的方法是:使用一个ORM类,为您抽象出特定的数据库差异。例如,你在PHP中得到这些( RedBean )Python(Django的ORM层, Storm , SqlAlchemy )Ruby on Rails( ActiveRecord ),可可( CoreData )

    即,您可以这样做:

    1. 使用ORM类从源数据库加载数据。
    2. 将数据存储在内存中或序列化到磁盘。
    3. 使用ORM类将数据存储到目标数据库中。
        3
  •  47
  •   community wiki 16 revs, 8 users 47% Jiaaro    8 年前

    这是一个python脚本,基于Shalmanese的回答和Alex martelli的一些帮助构建,网址为 Translating Perl to Python

    我正在把它变成社区维基,所以只要它不破坏功能,请随意编辑和重构(谢天谢地,我们可以回滚)——它很难看,但很有效

    这样使用(假设脚本被调用 dump_for_mysql.py :

    sqlite3 sample.db .dump | python dump_for_mysql.py > dump.sql
    

    然后,您可以将其导入mysql

    注意-您需要手动添加外键约束,因为sqlite实际上并不支持它们

    这是脚本:

    #!/usr/bin/env python
    
    import re
    import fileinput
    
    def this_line_is_useless(line):
        useless_es = [
            'BEGIN TRANSACTION',
            'COMMIT',
            'sqlite_sequence',
            'CREATE UNIQUE INDEX',
            'PRAGMA foreign_keys=OFF',
        ]
        for useless in useless_es:
            if re.search(useless, line):
                return True
    
    def has_primary_key(line):
        return bool(re.search(r'PRIMARY KEY', line))
    
    searching_for_end = False
    for line in fileinput.input():
        if this_line_is_useless(line):
            continue
    
        # this line was necessary because '');
        # would be converted to \'); which isn't appropriate
        if re.match(r".*, ''\);", line):
            line = re.sub(r"''\);", r'``);', line)
    
        if re.match(r'^CREATE TABLE.*', line):
            searching_for_end = True
    
        m = re.search('CREATE TABLE "?(\w*)"?(.*)', line)
        if m:
            name, sub = m.groups()
            line = "DROP TABLE IF EXISTS %(name)s;\nCREATE TABLE IF NOT EXISTS `%(name)s`%(sub)s\n"
            line = line % dict(name=name, sub=sub)
        else:
            m = re.search('INSERT INTO "(\w*)"(.*)', line)
            if m:
                line = 'INSERT INTO %s%s\n' % m.groups()
                line = line.replace('"', r'\"')
                line = line.replace('"', "'")
        line = re.sub(r"([^'])'t'(.)", "\1THIS_IS_TRUE\2", line)
        line = line.replace('THIS_IS_TRUE', '1')
        line = re.sub(r"([^'])'f'(.)", "\1THIS_IS_FALSE\2", line)
        line = line.replace('THIS_IS_FALSE', '0')
    
        # Add auto_increment if it is not there since sqlite auto_increments ALL
        # primary keys
        if searching_for_end:
            if re.search(r"integer(?:\s+\w+)*\s*PRIMARY KEY(?:\s+\w+)*\s*,", line):
                line = line.replace("PRIMARY KEY", "PRIMARY KEY AUTO_INCREMENT")
            # replace " and ' with ` because mysql doesn't like quotes in CREATE commands 
            if line.find('DEFAULT') == -1:
                line = line.replace(r'"', r'`').replace(r"'", r'`')
            else:
                parts = line.split('DEFAULT')
                parts[0] = parts[0].replace(r'"', r'`').replace(r"'", r'`')
                line = 'DEFAULT'.join(parts)
    
        # And now we convert it back (see above)
        if re.match(r".*, ``\);", line):
            line = re.sub(r'``\);', r"'');", line)
    
        if searching_for_end and re.match(r'.*\);', line):
            searching_for_end = False
    
        if re.match(r"CREATE INDEX", line):
            line = re.sub('"', '`', line)
    
        if re.match(r"AUTOINCREMENT", line):
            line = re.sub("AUTOINCREMENT", "AUTO_INCREMENT", line)
    
        print line,
    
        4
  •  22
  •   fguillen    12 年前

    我通常使用 Export/import tables 的特征 IntelliJ DataGrip .

    step 1 step 2 step 3

    您可以在右下角看到进度。

    [ enter image description here ]

        5
  •  8
  •   pdxleif    14 年前

    如果你正在使用Python/Dango,这很容易:

    在settings.py中创建两个数据库(如下所示 https://docs.djangoproject.com/en/1.11/topics/db/multi-db/ )

    那么就这样做:

    objlist = ModelObject.objects.using('sqlite').all()
    
    for obj in objlist:
        obj.save(using='mysql')
    
        6
  •  8
  •   Dashamir Hoxha    13 年前

    最简单的方法可能是使用sqlite.dump命令,在这种情况下创建示例数据库的转储。

    sqlite3 sample.db .dump > dump.sql
    

    然后,您可以(理论上)使用root用户将其导入mysql数据库,在本例中为数据库服务器127.0.0.1上的测试数据库。

    mysql -p -u root -h 127.0.0.1 test < dump.sql
    

    我说在理论上,因为语法之间存在一些差异。

    在sqlite中,事务开始

    BEGIN TRANSACTION;
    ...
    COMMIT;
    

    MySQL仅使用

    BEGIN;
    ...
    COMMIT;
    

    还有其他类似的问题(varchars和双引号又浮现在脑海中),但没有任何查找和替换无法解决的问题。

    也许你应该问为什么要迁移,如果性能/数据库大小是问题所在,也许可以考虑重新启动模式,如果系统正在转向更强大的产品,这可能是规划数据未来的理想时机。

        7
  •  7
  •   Community CDub    8 年前

    我刚刚经历了这个过程,这个问答中有很多很好的帮助和信息,但我发现我必须将各种元素(加上其他问答中的一些元素)整合在一起,才能得到一个有效的解决方案,才能成功迁移。

    然而,即使在结合了现有的答案后,我发现Python脚本对我来说也不完全有效,因为在INSERT中有多个布尔值出现的情况下它不起作用。看见 here 为什么会这样。

    所以,我想在这里发布我的合并答案。当然,这要归功于那些在其他地方做出贡献的人。但我想回馈一些东西,并为其他人节省时间。

    我会把剧本贴在下面。但首先,这是转换的说明。..

    我在OS X 10.7.5 Lion上运行了这个脚本。Python开箱即用。

    要从现有的SQLite3数据库生成MySQL输入文件,请在自己的文件上运行脚本,如下所示:,

    Snips$ sqlite3 original_database.sqlite3 .dump | python ~/scripts/dump_for_mysql.py > dumped_data.sql
    

    然后,我将得到的dumped_sql.sql文件复制到运行Ubuntu 10.04.4 LTS的Linux机器上,我的MySQL数据库将驻留在那里。

    导入MySQL文件时遇到的另一个问题是,一些unicode UTF-8字符(特别是单引号)没有正确导入,因此我不得不在命令中添加一个开关来指定UTF-8。

    将数据输入一个全新的空MySQL数据库的命令如下:

    Snips$ mysql -p -u root -h 127.0.0.1 test_import --default-character-set=utf8 < dumped_data.sql
    

    让它煮吧,应该就是这样!别忘了在之前和之后仔细检查你的数据。

    因此,正如OP所要求的那样,当你知道如何操作时,它既快捷又简单! :-)

    顺便说一句,在我研究这次迁移之前,有一件事我不确定,那就是created_at和updated_at字段值是否会被保留——对我来说,好消息是它们会被保留,所以我可以迁移我现有的生产数据。

    祝你好运

    更新

    自从切换后,我注意到了一个以前没有注意到的问题。在我的Rails应用程序中,我的文本字段被定义为“string”,这一直延续到数据库模式。这里概述的过程导致这些在MySQL数据库中被定义为VARCHAR(255)。这对这些字段大小设置了255个字符的限制,超出此限制的任何内容在导入过程中都会被自动截断。我认为,为了支持大于255的文本长度,MySQL模式需要使用“text”而不是VARCHAR(255)。此处定义的过程不包括此转换。


    以下是对我的数据有效的合并和修订的Python脚本:

    #!/usr/bin/env python
    
    import re
    import fileinput
    
    def this_line_is_useless(line):
        useless_es = [
            'BEGIN TRANSACTION',
            'COMMIT',
            'sqlite_sequence',
            'CREATE UNIQUE INDEX',        
            'PRAGMA foreign_keys=OFF'
            ]
        for useless in useless_es:
            if re.search(useless, line):
                return True
    
    def has_primary_key(line):
        return bool(re.search(r'PRIMARY KEY', line))
    
    searching_for_end = False
    for line in fileinput.input():
        if this_line_is_useless(line): continue
    
        # this line was necessary because ''); was getting
        # converted (inappropriately) to \');
        if re.match(r".*, ''\);", line):
            line = re.sub(r"''\);", r'``);', line)
    
        if re.match(r'^CREATE TABLE.*', line):
            searching_for_end = True
    
        m = re.search('CREATE TABLE "?([A-Za-z_]*)"?(.*)', line)
        if m:
            name, sub = m.groups()
            line = "DROP TABLE IF EXISTS %(name)s;\nCREATE TABLE IF NOT EXISTS `%(name)s`%(sub)s\n"
            line = line % dict(name=name, sub=sub)
            line = line.replace('AUTOINCREMENT','AUTO_INCREMENT')
            line = line.replace('UNIQUE','')
            line = line.replace('"','')
        else:
            m = re.search('INSERT INTO "([A-Za-z_]*)"(.*)', line)
            if m:
                line = 'INSERT INTO %s%s\n' % m.groups()
                line = line.replace('"', r'\"')
                line = line.replace('"', "'")
                line = re.sub(r"(?<!')'t'(?=.)", r"1", line)
                line = re.sub(r"(?<!')'f'(?=.)", r"0", line)
    
        # Add auto_increment if it's not there since sqlite auto_increments ALL
        # primary keys
        if searching_for_end:
            if re.search(r"integer(?:\s+\w+)*\s*PRIMARY KEY(?:\s+\w+)*\s*,", line):
                line = line.replace("PRIMARY KEY", "PRIMARY KEY AUTO_INCREMENT")
            # replace " and ' with ` because mysql doesn't like quotes in CREATE commands
    
        # And now we convert it back (see above)
        if re.match(r".*, ``\);", line):
            line = re.sub(r'``\);', r"'');", line)
    
        if searching_for_end and re.match(r'.*\);', line):
            searching_for_end = False
    
        if re.match(r"CREATE INDEX", line):
            line = re.sub('"', '`', line)
    
        print line,
    
        8
  •  6
  •   Patrick Garner    8 年前
    aptitude install sqlfairy libdbd-sqlite3-perl
    
    sqlt -f DBI --dsn dbi:SQLite:../.open-tran/ten-sq.db -t MySQL --add-drop-table > mysql-ten-sq.sql
    sqlt -f DBI --dsn dbi:SQLite:../.open-tran/ten-sq.db -t Dumper --use-same-auth > sqlite2mysql-dumper.pl
    chmod +x sqlite2mysql-dumper.pl
    ./sqlite2mysql-dumper.pl --help
    ./sqlite2mysql-dumper.pl --add-truncate --mysql-loadfile > mysql-dump.sql
    sed -e 's/LOAD DATA INFILE/LOAD DATA LOCAL INFILE/' -i mysql-dump.sql
    
    echo 'drop database `ten-sq`' | mysql -p -u root
    echo 'create database `ten-sq` charset utf8' | mysql -p -u root
    mysql -p -u root -D ten-sq < mysql-ten-sq.sql
    mysql -p -u root -D ten-sq < mysql-dump.sql
    
        9
  •  5
  •   Tim Frey    17 年前

    我用Python3写了这个简单的脚本。它可以用作包含的类或通过终端shell调用的独立脚本。默认情况下,它将所有整数导入为 int(11) 和字符串作为 varchar(300) ,但所有这些都可以分别在构造函数或脚本参数中进行调整。

    注: 它需要MySQL连接器/Python 2.0.4或更高版本

    如果你觉得下面的代码很难阅读,这里有一个指向GitHub上源代码的链接: https://github.com/techouse/sqlite3-to-mysql

    #!/usr/bin/env python3
    
    __author__ = "Klemen Tušar"
    __email__ = "techouse@gmail.com"
    __copyright__ = "GPL"
    __version__ = "1.0.1"
    __date__ = "2015-09-12"
    __status__ = "Production"
    
    import os.path, sqlite3, mysql.connector
    from mysql.connector import errorcode
    
    
    class SQLite3toMySQL:
        """
        Use this class to transfer an SQLite 3 database to MySQL.
    
        NOTE: Requires MySQL Connector/Python 2.0.4 or higher (https://dev.mysql.com/downloads/connector/python/)
        """
        def __init__(self, **kwargs):
            self._properties = kwargs
            self._sqlite_file = self._properties.get('sqlite_file', None)
            if not os.path.isfile(self._sqlite_file):
                print('SQLite file does not exist!')
                exit(1)
            self._mysql_user = self._properties.get('mysql_user', None)
            if self._mysql_user is None:
                print('Please provide a MySQL user!')
                exit(1)
            self._mysql_password = self._properties.get('mysql_password', None)
            if self._mysql_password is None:
                print('Please provide a MySQL password')
                exit(1)
            self._mysql_database = self._properties.get('mysql_database', 'transfer')
            self._mysql_host = self._properties.get('mysql_host', 'localhost')
    
            self._mysql_integer_type = self._properties.get('mysql_integer_type', 'int(11)')
            self._mysql_string_type = self._properties.get('mysql_string_type', 'varchar(300)')
    
            self._sqlite = sqlite3.connect(self._sqlite_file)
            self._sqlite.row_factory = sqlite3.Row
            self._sqlite_cur = self._sqlite.cursor()
    
            self._mysql = mysql.connector.connect(
                user=self._mysql_user,
                password=self._mysql_password,
                host=self._mysql_host
            )
            self._mysql_cur = self._mysql.cursor(prepared=True)
            try:
                self._mysql.database = self._mysql_database
            except mysql.connector.Error as err:
                if err.errno == errorcode.ER_BAD_DB_ERROR:
                    self._create_database()
                else:
                    print(err)
                    exit(1)
    
        def _create_database(self):
            try:
                self._mysql_cur.execute("CREATE DATABASE IF NOT EXISTS `{}` DEFAULT CHARACTER SET 'utf8'".format(self._mysql_database))
                self._mysql_cur.close()
                self._mysql.commit()
                self._mysql.database = self._mysql_database
                self._mysql_cur = self._mysql.cursor(prepared=True)
            except mysql.connector.Error as err:
                print('_create_database failed creating databse {}: {}'.format(self._mysql_database, err))
                exit(1)
    
        def _create_table(self, table_name):
            primary_key = ''
            sql = 'CREATE TABLE IF NOT EXISTS `{}` ( '.format(table_name)
            self._sqlite_cur.execute('PRAGMA table_info("{}")'.format(table_name))
            for row in self._sqlite_cur.fetchall():
                column = dict(row)
                sql += ' `{name}` {type} {notnull} {auto_increment}, '.format(
                    name=column['name'],
                    type=self._mysql_string_type if column['type'].upper() == 'TEXT' else self._mysql_integer_type,
                    notnull='NOT NULL' if column['notnull'] else 'NULL',
                    auto_increment='AUTO_INCREMENT' if column['pk'] else ''
                )
                if column['pk']:
                    primary_key = column['name']
            sql += ' PRIMARY KEY (`{}`) ) ENGINE = InnoDB CHARACTER SET utf8'.format(primary_key)
            try:
                self._mysql_cur.execute(sql)
                self._mysql.commit()
            except mysql.connector.Error as err:
                print('_create_table failed creating table {}: {}'.format(table_name, err))
                exit(1)
    
        def transfer(self):
            self._sqlite_cur.execute("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'")
            for row in self._sqlite_cur.fetchall():
                table = dict(row)
                # create the table
                self._create_table(table['name'])
                # populate it
                print('Transferring table {}'.format(table['name']))
                self._sqlite_cur.execute('SELECT * FROM "{}"'.format(table['name']))
                columns = [column[0] for column in self._sqlite_cur.description]
                try:
                    self._mysql_cur.executemany("INSERT IGNORE INTO `{table}` ({fields}) VALUES ({placeholders})".format(
                        table=table['name'],
                        fields=('`{}`, ' * len(columns)).rstrip(' ,').format(*columns),
                        placeholders=('%s, ' * len(columns)).rstrip(' ,')
                    ), (tuple(data) for data in self._sqlite_cur.fetchall()))
                    self._mysql.commit()
                except mysql.connector.Error as err:
                    print('_insert_table_data failed inserting data into table {}: {}'.format(table['name'], err))
                    exit(1)
            print('Done!')
    
    
    def main():
        """ For use in standalone terminal form """
        import sys, argparse
        parser = argparse.ArgumentParser()
        parser.add_argument('--sqlite-file', dest='sqlite_file', default=None, help='SQLite3 db file')
        parser.add_argument('--mysql-user', dest='mysql_user', default=None, help='MySQL user')
        parser.add_argument('--mysql-password', dest='mysql_password', default=None, help='MySQL password')
        parser.add_argument('--mysql-database', dest='mysql_database', default=None, help='MySQL host')
        parser.add_argument('--mysql-host', dest='mysql_host', default='localhost', help='MySQL host')
        parser.add_argument('--mysql-integer-type', dest='mysql_integer_type', default='int(11)', help='MySQL default integer field type')
        parser.add_argument('--mysql-string-type', dest='mysql_string_type', default='varchar(300)', help='MySQL default string field type')
        args = parser.parse_args()
    
        if len(sys.argv) == 1:
            parser.print_help()
            exit(1)
    
        converter = SQLite3toMySQL(
            sqlite_file=args.sqlite_file,
            mysql_user=args.mysql_user,
            mysql_password=args.mysql_password,
            mysql_database=args.mysql_database,
            mysql_host=args.mysql_host,
            mysql_integer_type=args.mysql_integer_type,
            mysql_string_type=args.mysql_string_type
        )
        converter.transfer()
    
    if __name__ == '__main__':
        main()
    
        10
  •  5
  •   Richard Gourlay    17 年前

    我最近不得不为我们团队正在进行的一个项目从MySQL迁移到JavaDB Java library written by Apache called DdlUtils 这让事情变得相当容易。它提供了一个API,可以让您执行以下操作:

    1. 发现数据库的模式并将其导出为XML文件。
    2. 根据此架构修改数据库。
    3. 将记录从一个数据库导入另一个数据库,假设它们具有相同的模式。

    我们最终得到的工具并没有完全自动化,但它们工作得很好。即使您的应用程序不是用Java编写的,也不难使用一些小工具进行一次性迁移。我想我能够用不到150行的代码完成我们的迁移。

        11
  •  5
  •   Mihkorz    8 年前

    获取SQL转储

    moose@pc08$ sqlite3 mySqliteDatabase.db .dump > myTemporarySQLFile.sql
    

    将转储导入MySQL

    对于小型进口:

    moose@pc08$ mysql -u <username> -p
    Enter password:
    ....
    mysql> use somedb;
    Database changed
    mysql> source myTemporarySQLFile.sql;
    

    mysql -u root -p somedb < myTemporarySQLFile.sql
    

    这将提示您输入密码。请注意:如果你想直接输入密码,你必须在没有空格的情况下直接输入 -p :

    mysql -u root -pYOURPASS somedb < myTemporarySQLFile.sql
    

    对于较大的垃圾场:

    mysqlimport或其他导入工具,如 BigDump .

    BigDump会给你一个进度条:

    enter image description here

        12
  •  4
  •   Martin Thoma    12 年前

    基于Jims的解决方案: Quick easy way to migrate SQLite3 to MySQL?

    sqlite3 your_sql3_database.db .dump | python ./dump.py > your_dump_name.sql
    cat your_dump_name.sql | sed '1d' | mysql --user=your_mysql_user --default-character-set=utf8 your_mysql_db -p  
    

    这对我来说很有效。我使用sed只是抛出第一行,这与mysql不同,但你也可以修改dump.py脚本来扔掉这一行。

        13
  •  3
  •   Andy Ali    10 年前

    不需要任何脚本、命令等。。。

    您只需将sqlite数据库导出为 .csv 文件,然后使用phpmyadmin将其导入Mysql。

    我用过它,它效果很好。..

        14
  •  2
  •   J vincent    16 年前

    哈。..我真希望我先找到这个!我的回应是针对这篇文章。.. script to convert mysql dump sql file into format that can be imported into sqlite3 db

    将两者结合正是我所需要的:


    当sqlite3数据库将与ruby一起使用时,您可能需要更改:

    tinyint([0-9]*) 
    

    致:

    sed 's/ tinyint(1*) / boolean/g ' |
    sed 's/ tinyint([0|2-9]*) / integer /g' |
    

    唉,这只起了一半的作用,因为即使你将1和0插入到标记为boolean的字段中,sqlite3也会将它们存储为1和0,所以你必须遍历并执行以下操作:

    Table.find(:all, :conditions => {:column => 1 }).each { |t| t.column = true }.each(&:save)
    Table.find(:all, :conditions => {:column => 0 }).each { |t| t.column = false}.each(&:save)
    

    但是查看sql文件以查找所有布尔值是有帮助的。

        15
  •  2
  •   Community CDub    8 年前

    这个脚本是可以的,除了这个情况,当然,我见过:

    INSERT INTO "requestcomparison_stopword" VALUES(149,'f');
    INSERT INTO "requestcomparison_stopword" VALUES(420,'t');
    

    脚本应给出以下输出:

    INSERT INTO requestcomparison_stopword VALUES(149,'f');
    INSERT INTO requestcomparison_stopword VALUES(420,'t');
    

    但给出了这样的输出:

    INSERT INTO requestcomparison_stopword VALUES(1490;
    INSERT INTO requestcomparison_stopword VALUES(4201;
    

    最后0和1周围有一些奇怪的非ascii字符。

    当我注释以下代码行(43-46)时,这不再出现,但出现了其他问题:

    
        line = re.sub(r"([^'])'t'(.)", "\1THIS_IS_TRUE\2", line)
        line = line.replace('THIS_IS_TRUE', '1')
        line = re.sub(r"([^'])'f'(.)", "\1THIS_IS_FALSE\2", line)
        line = line.replace('THIS_IS_FALSE', '0')
    

    这只是一个特例,当我们想添加一个值为'f'或't',但我对正则表达式不太熟悉时,我只是想发现这个情况需要有人纠正。

    不管怎样,非常感谢这个方便的脚本!!!

        16
  •  2
  •   NavidIvanian    9 年前

    这个简单的解决方案对我很有效:

    <?php
    $sq = new SQLite3( 'sqlite3.db' );
    
    $tables = $sq->query( 'SELECT name FROM sqlite_master WHERE type="table"' );
    
    while ( $table = $tables->fetchArray() ) {
        $table = current( $table );
        $result = $sq->query( sprintf( 'SELECT * FROM %s', $table ) );
    
        if ( strpos( $table, 'sqlite' ) !== false )
            continue;
    
        printf( "-- %s\n", $table );
        while ( $row = $result->fetchArray( SQLITE3_ASSOC ) ) {
            $values = array_map( function( $value ) {
                return sprintf( "'%s'", mysql_real_escape_string( $value ) );
            }, array_values( $row ) );
            printf( "INSERT INTO `%s` VALUES( %s );\n", $table, implode( ', ', $values ) );
        }
    }
    
        17
  •  1
  •   Community CDub    8 年前
    echo ".dump" | sqlite3 /tmp/db.sqlite > db.sql
    

    注意CREATE语句

        18
  •  1
  •   Snips    12 年前
        19
  •  1
  •   Dung    10 年前
        20
  •  0
  •   fallino    15 年前
        21
  •  0
  •   soulseekah    9 年前
        22
  •  0
  •   Community CDub    8 年前
        23
  •  0
  •   Klemen Tusar    7 年前
        24
  •  0
  •   Vincent Sit    6 年前
        25
  •  -1
  •   Community CDub    8 年前
        26
  •  -5
  •   RichardTheKiwi    12 年前
    推荐文章