如果该列已经存在,我想更改一个表。如果没有,我想添加它。
我的代码是:
-(void) alterDB{
sqlite3_stmt *statement;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:DATABASE_NAME];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
{
NSString *updateSQL = [NSString stringWithFormat: @"ALTER TABLE diagramInfo ADD COLUMN testColumn VARCHAR"];
const char *update_stmt = [updateSQL UTF8String];
sqlite3_prepare_v2(database, update_stmt, -1, &statement, NULL);
if(sqlite3_step(statement)==SQLITE_DONE)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"DB altered" message:@"Success" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert=nil;
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"DB Updation" message:@"DB not Altered" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
alert=nil;
}
// Release the compiled statement from memory
sqlite3_finalize(statement);
sqlite3_close(database);
}
}
2条答案
按热度按时间mpgws1up1#
使用以下函数检查列是否存在。实际上没有检查,所以您可能需要检查语法。概念类似于如果您能够创建预准备语句而不是列存在,否则就不能。
SWIFT 3.2:
km0tfn4u2#
PRAGMA table_info(table-name);
此Pragma用于获取表中的列的列表。
有关更多详细信息,请参阅SQLite>Pragma语句>TABLE_INFO文档。