Export a MySQL Database to SQLite Database

前端 未结 7 1399
太阳男子
太阳男子 2020-11-28 08:33

Please help me with exporting a MySQL database into a SQLite database.

7条回答
  •  情歌与酒
    2020-11-28 09:10

    The answer by @user2111698 edited by @quassy works as promised. Since I do this frequently I put their instructions into a bash script:

    #!/bin/bash
    
    mysql_host=localhost
    mysql_user=george
    mysql_dbname=database
    sqlite3_dbname=database.sqlite3
    
    # dump the mysql database to a txt file
    mysqldump \
      --skip-create-options \
      --compatible=ansi \
      --skip-extended-insert \
      --compact \
      --single-transaction \
      -h$mysql_host \
      -u$mysql_user \
      -p $mysql_dbname \
      > /tmp/localdb.txt
    
    # remove lines mentioning "PRIMARY KEY" or "KEY"
    cat /tmp/localdb.txt \
      | grep -v "PRIMARY KEY" \
      | grep -v KEY \
      > /tmp/localdb.txt.1
    
    # mysqldump leaves trailing commas before closing parentheses  
    perl -0pe 's/,\n\)/\)/g' /tmp/localdb.txt.1 > /tmp/localdb.txt.2
    
    # change all \' to ''
    sed -e 's/\\'\''/'\'''\''/g' /tmp/localdb.txt.2 > /tmp/localdb.txt.3
    
    if [ -e $sqlite3_dbname ]; then
        mv $sqlite3_dbname $sqlite3_dbname.bak
    fi
    sqlite3 $sqlite3_dbname < /tmp/localdb.txt.3
    

    A gist with detailed comments can be found at https://gist.github.com/grfiv/b79ace3656113bcfbd9b7c7da8e9ae8d

提交回复
热议问题