246

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

4

17 回答 17

123

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

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

  • 开始交易
  • 犯罪
  • sqlite_sequence
  • 创建唯一索引

未在 MySQL 中使用

  • SQLite 使用CREATE TABLE/INSERT INTO "table_name"和 MySQL 使用CREATE TABLE/INSERT INTO table_name
  • MySQL 不在模式定义中使用引号
  • INSERT INTOMySQL 对子句中的字符串使用单引号
  • SQLite 和 MySQL 在INSERT INTO子句中转义字符串的方式不同
  • SQLite 使用't'and'f'来表示布尔值,MySQL 使用1and 0(当你有一个像这样的字符串时,一个简单的正则表达式可能会失败:'I do, you don't' inside your INSERT INTO
  • 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;
    }
}
于 2008-09-17T20:49:49.620 回答
65

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


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

即你可以这样做:

  1. 使用 ORM 类从源数据库加载数据。
  2. 将数据存储在内存中或序列化到磁盘。
  3. 使用 ORM 类将数据存储到目标数据库中。
于 2011-05-14T07:11:45.367 回答
55

这是一个 python 脚本,基于 Shalmanese 的回答和 Alex martelli 在Translating Perl to Python中的一些帮助

我正在制作它的社区 wiki,所以请随时编辑和重构,只要它不破坏功能(谢天谢地我们可以回滚) - 它非常丑陋但有效

像这样使用(假设脚本被调用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,
于 2009-07-01T05:09:37.147 回答
20

我通常使用IntelliJ DataGrip的导出/导入表功能。

第1步 第2步 第 3 步

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

[ 在此处输入图像描述]

于 2018-10-16T16:33:01.090 回答
16

如果您使用的是 Python/Django,这很容易:

在 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')
于 2017-07-12T15:32:34.230 回答
12

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

sqlite3 sample.db .dump > dump.sql

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

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

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

在 sqlite 事务开始

BEGIN TRANSACTION;
...
COMMIT;

MySQL 只使用

BEGIN;
...
COMMIT;

还有其他类似的问题(varchars 和双引号回想起),但没有什么 find 和 replace 无法解决。

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

于 2008-08-25T11:10:04.650 回答
10

我刚刚经历了这个过程,在这个 Q/A 中有很多非常好的帮助和信息,但我发现我必须将各种元素(加上其他 Q/A 中的一些元素)放在一起才能获得一个可行的解决方案才能成功迁移。

然而,即使在结合现有答案之后,我发现 Python 脚本并不能完全为我工作,因为它在 INSERT 中出现多个布尔值时不起作用。看看这里为什么会这样。

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

我将在下面发布脚本。但首先,这是转换的说明......

我在 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 应用程序中,我的文本字段被定义为“字符串”,这会传递到数据库模式。此处概述的过程导致这些在 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,
于 2012-11-13T17:06:15.117 回答
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
于 2011-10-12T22:01:46.553 回答
5

我最近不得不从 MySQL 迁移到 JavaDB,以完成我们团队正在进行的项目。我发现了一个由 Apache 编写的名为 DdlUtils 的 Java 库,它使这变得非常容易。它提供了一个 API,可让您执行以下操作:

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

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

于 2008-08-21T03:12:51.460 回答
5

获取 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 给你一个进度条:

在此处输入图像描述

于 2013-06-09T12:01:37.000 回答
5

我用 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()
于 2015-08-27T08:09:54.267 回答
4

基于 Jims 的解决方案: 将 SQLite3 迁移到 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 脚本以将这一行扔掉。

于 2011-06-20T12:12:52.507 回答
3

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

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

我用过它,它的效果很棒......

于 2016-07-16T18:54:15.830 回答
1

哈...我希望我先找到这个!我对这篇文章的回应是...脚本将 mysql 转储 sql 文件转换为可以导入 sqlite3 db 的格式

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


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

tinyint([0-9]*) 

到:

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

唉,这只有一半有效,因为即使您将 1 和 0 插入标记为布尔值的字段,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 文件以查找所有布尔值是有帮助的。

于 2010-03-30T06:32:32.787 回答
0

这个脚本没问题,除了我遇到的这种情况:

插入“requestcomparison_stopword”值(149,'f');
插入“requestcomparison_stopword”值(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' 但我对正则表达式不太满意时,我只是想发现这种情况以供某人纠正。

无论如何,非常感谢那个方便的脚本!

于 2009-09-30T14:42:45.223 回答
0

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

<?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 ) );
    }
}
于 2015-11-19T06:41:00.427 回答
-6
echo ".dump" | sqlite3 /tmp/db.sqlite > db.sql

注意 CREATE 语句

于 2012-04-08T22:32:40.023 回答