Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check If column already exist and if not Alter Table in sqlite

I want to alter a table of sqlite in my app.

now , i want to check that if that column already exists in my table or not ?

hence if not exist i want to add that column with alter table syntex.

currently i am using .

-(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);
    }
}
like image 239
PJR Avatar asked Apr 02 '12 06:04

PJR


People also ask

How do you check if a table already exists in SQLite?

In an SQLite database, the names of all the tables are enlisted in the sqlite_master table. So in order to check if a table exists or not we need to check that if the name of the particular table is in the sqlite_master table or not.

How do you check a column exists in SQL database?

Checking Existence of the Column: Now we use the below query to check the existence of a column. Query: IF COL_LENGTH('table_name','column_name') IS NOT NULL PRINT 'Column Exists'; ELSE PRINT 'Column does not Exists';

Does SQLite have Information_schema?

There is no information_schema in SQLite as pointed out by @mustaccio. However, you can get the information you require by using this SQL: SELECT name FROM sqlite_master WHERE type ='table' AND name NOT LIKE 'sqlite_%'; See the link here.

How can I see the columns of a table in SQLite?

PRAGMA table_info(table_name); will get you a list of all the column names.


2 Answers

Use following function for checking if column exists. Not checked practically so you may have to check syntax. Concept is like if you are able to create prepared statement than column exists otherwise not.

-(BOOL)checkColumnExists
{
    BOOL columnExists = NO;

    sqlite3_stmt *selectStmt;

    const char *sqlStatement = "select yourcolumnname from yourtable";
    if(sqlite3_prepare_v2(yourDbHandle, sqlStatement, -1, &selectStmt, NULL) == SQLITE_OK)
        columnExists = YES;

    return columnExists;
}

Swift 3.2:

private func tableHasColumn(db: OpaquePointer, tableName: String, columnName: String) -> Bool {

        var retVal = false

        var tableColumnsQueryStatement: OpaquePointer? = nil
        if sqlite3_prepare_v2(db, "PRAGMA table_info(\(tableName));",
                            -1,
                            &tableColumnsQueryStatement,
                            nil) == SQLITE_OK {

            while (sqlite3_step(tableColumnsQueryStatement) == SQLITE_ROW) {

                let queryResultCol1 = sqlite3_column_text(tableColumnsQueryStatement, 1)
                let currentColumnName = String(cString: queryResultCol1!)

                if currentColumnName == columnName {
                    retVal = true
                    break
                }
            }
        }

        return retVal
}
like image 129
Janak Nirmal Avatar answered Sep 24 '22 22:09

Janak Nirmal


PRAGMA table_info(table-name);

This Pragma is used to get list of columns in your table.

For more details, visit here

- (BOOL)checkForField
{
    NSString *desiredColumn = @"tblName";
    const char *sql = "PRAGMA table_info(tblTest)";
    sqlite3_stmt *stmt;

    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK)
    {
        return NO;
    }

    while(sqlite3_step(stmt) == SQLITE_ROW)
    {

        NSString *fieldName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(stmt, 1)];
        if([desiredColumn isEqualToString:fieldName])
            return YES;
    }

    return NO;
}
like image 38
DivineDesert Avatar answered Sep 24 '22 22:09

DivineDesert