sqlite3 to mysql_将SQLite3迁移到MySQL的快速简便方法?

本文提供了一个Python脚本,用于将SQLite3数据库迁移到MySQL。脚本基于Shalmanese和Alex Martelli的建议,通过读取SQLite3的dump文件并进行必要的格式转换,然后将数据导入到MySQL。用户需要手动添加外键约束,因为SQLite3不支持此功能。脚本处理了包括去除不必要的语句、转换数据类型和创建表的语句等步骤。
摘要由CSDN通过智能技术生成

这是一个python脚本,基于Shalmanese的答案和Alex martelli在翻译Perl到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 = Falsefor 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,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值