Today I had to migrate a MySQL table to SQLite so that I could use it in an iPhone app. The process is simple, you can export the MySQL table and then import it in SQLite. I found the following shell script in the MySQL site (I think), but the resulting file could not be imported in SQLite, since I had used the MySQL COMMENT to document each of the columns. SQLite does not understand column comments. So here is the updated script that makes the MYSQL dump work with SQLite.
#!/bin/sh
/opt/local/lib/mysql5/bin/mysqldump --compact --compatible=ansi --default-character-set=binary -uUSERNAME -pPASSWORD DATABASE TABLE |
sed -e "s/COMMENT '.*',/,/" |
grep -v ' KEY "' |
grep -v ' UNIQUE KEY "' |
perl -e 'local $/;$_=<>;s/,\n\)/\n\)/gs;print "begin;\n";print;print "commit;\n"' |
perl -pe '
if (/^(INSERT.+?)\(/) {
$a=$1;
s/\\'\''/'\'\''/g;
s/\\n/\n/g;
s/\),\(/\);\n$a\(/g;
}
' > db.sql
You must substitute the USERNAME, PASSWORD, DATABASE and TABLE with the values for your project.
Next, you need to load this dump file into SQLite, issue the following command:
cat db.sql | sqlite3 db.db
This will create a SQLite database in a file called db.db. Now you can add the file db.db to your iPhone project, plus add the SQLite3 iphone framework and finally you’ll be ready to use the database from Objective-C.
August 6, 2011 at 10:24 pm |
Hello. Thanks for the script. It worked perfectly to create the dump. However, when I ran the second command:
cat db.sql | sqlite3 db.db
I received the following error:
SQL error: no such table: events
Am I doing something wrong? Thanks for your help!
August 6, 2011 at 10:33 pm |
Hello. Not sure. I’m afraid you will need to debug it. Try just importing the schema (without the data) and then check to see if the tables are created or not. Good luck.
August 7, 2011 at 12:07 am |
Ok, was able to get it imported. Two things sqlite didn’t like from the original dump file….timestamp field and field comments. Once I deleted those it copied over fine.
YAY! I have been working on getting mysql data into sqlite for two weeks now….whew!