0

我有一个 .sql 文件,其中包含数据库中表的所有创建语句(即 CREATE TABLE X、CREATE INDEX Y、CREATE UNIQUE INDEX Z)。是否可以编写一个可以轻松运行此代码并生成表的makefile?

此外,是否可以将其连接到 Xcode,以便在我运行我的应用程序时创建数据库?

4

1 回答 1

3

Use sqlite3_exec to run your sql file at runtime in your app. Of course you only want to do it once. You need to use sqlite2_open_v2 to open a new database file first, then execute the sql file.

If you want to generate the database file in Xcode during a build, you can do this after some setup. I do this in one of my projects.

Start by selecting your target in Xcode and going to the "Build Phases" tab. Then click on the "Add Build Phase" button and select "Add Run Script". Double-click on the "Run Script" title and rename it to something useful such as "Generate db file".

Change the "shell" value to "/bin/bash".

Use the following for the script:

cd database
if [ create.sql -nt data.db ]; then
   rm -rf empty.db
fi

if [ ! -e data.db ]; then
   sqlite3 data.db < create.sql
fi
cd -

You probably need to change a few details of this script. Given that the script will be run from the root directory of your project, change the first line (cd database) to reflect where your sql file is within your own project. Then change any references to create.sql to match the name of your own sql file. And last, change any references to data.db to match what you want your database file to be named.

The last step is to move this build phase to before the "Copy Bundle Resources" phase. Also make sure the db file ends up in your resources.

The script will update the db file any time the sql file is updated.

于 2013-06-19T01:51:03.097 回答