欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

sqlite迁移到mysql脚本的方法

程序员文章站 2022-06-29 14:45:09
废话不多说了,直接给大家贴代码了,具体代码如下所示: #! /usr/bin/perl # # based on https://*....

废话不多说了,直接给大家贴代码了,具体代码如下所示:

#! /usr/bin/perl
#
# based on https://*.com/a/87531/5742651
# usage: sqlite3 .dump database_name.sqlite3 | perl sqlite2mysql.pl | mysql -u root -p $import_database_name
#
# ignore follow lines:
#  begin transaction 
#  commit 
#  sqlite_sequence 
#  create unique index
#  pragma foreign_keys=off
# "tablename/field" => `tablename/field`
# booleans 't' and 'f' => 1 and 0
# autoincrement => auto_increment
# varchar => varchar(255)
# create table table... => drop table table; create table table...
# merge insert sqls into multiple insert to speed up
#  insert into table values('val1');
#  insert into table values('val2');  => insert into table values('val1'), ('val2'), ('val3');
#  insert into table values('val3');
my $open=0;
my $line_cache = '';
# for speed up
print "set global max_allowed_packet=209715200;\n";
#print "set autocommit=0;\n";
while ($line = <>){
  if (($line !~ /pragma foreign_keys=off/) && ($line !~ /begin transaction/) && ($line !~ /commit/) && ($line !~ /sqlite_sequence/) && ($line !~ /create unique index/)){
   if ($line =~ /create table \"([a-z_0-9]*)\"(.*)/){
   $name = "\`$1\`";
   $sub = $2;
   $sub =~ s/varchar([^(])/varchar(255)$1/g;
   $line = "drop table if exists $name;\ncreate table $name$sub\n"; 
   }
   elsif ($line =~ /create view ([a-z_0-9]*)(.*)/){
   $name = "\`$1\`";
   $sub = $2;
   $line = "drop view if exists $name;\ncreate view $name$sub\n";
   }
   elsif ($line =~ /insert into \"([a-z_]*)\" values(.*);/){
        if ($open == 0) {
          $open = 1;
       $line_cache .= "insert into \`$1\` values $2";
        } else {
          $line_cache .= ", $2";
        }
        next;
   }else{
   $line =~ s/\'\'/\\\'/g;
   }
    if ($open == 1) {
       $open = 0;
       $line = $line_cache.";\n".$line;
       $line_cache = '';
    }
   $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;
  }
}
#print "set autocommit=1;\n";

总结

以上所述是小编给大家介绍的sqlite迁移到mysql脚本的方法,希望对大家有所帮助