sqlite3 用代码创建数据库 和 表 ios

时间:2023-01-10 23:06:57

首先要引入SQLite 3.0 的lib库,并包含头文件


// 功能:创建SqliteDB
// 参数:无
// 返回值:是否创建成功
-(BOOL)CreatSqliteDB
{
sqlite3 *db;
char *zErrMsg = 0;
int rc;

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:kDB_Name];

/*创建数据库kDB_Name*/
rc = sqlite3_open([path UTF8String], &db);
if( rc )
{
printf("Can't open database: %s\n", sqlite3_errmsg(db));
sqlite3_close(db);
}


/*创建建表1*/
NSString *filetable = @"CREATE TABLE mesfile (ID Varchar(20) PRIMARY KEY DEFAULT NULL,name Varchar(255),dir Varchar(255),size rchar(255),creationTime Varchar(32),modificationTime Varchar(32),shared Varchar(8) DEFAULT NULL,shareByName Varchar(20),shareById Varchar(20),url Varchar(255),md5 Varchar(32),type Varchar(5) DEFAULT NULL,favorite Varchar(5) DEFAULT NULL,userID Varchar(20) DEFAULT NULL)";
rc = sqlite3_exec(db, [filetable UTF8String], NULL, 0, &zErrMsg);
if( rc!=SQLITE_OK )
{
printf("SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
return NO;
}

/*创建建表2*/
rc = sqlite3_exec(db, "CREATE TABLE file2(a NUMERIC, b TEXT)", NULL, 0, &zErrMsg);
if( rc!=SQLITE_OK )
{
printf("SQL error: %s\n", zErrMsg);
sqlite3_free(zErrMsg);
return NO;
}

sqlite3_close(db);

return YES;
}

已验证~