Shanmugaraja G
Shanmugaraja G

Reputation: 2778

I want to check whether a primary key exists on sqlite table

I have an sqlite database on my Iphone app. That database has a table named "Students" and It has 10 rows of data with keys from 1 to 11. But I want to test whether a primary key with value "3" exists on the table by objective c coding.

Upvotes: 2

Views: 3576

Answers (2)

JeremyP
JeremyP

Reputation: 86651

You need to run a select query on it. The in depth info on how to do that is here.

The basic steps are:

  • open the database
  • prepare a select statement
  • bind host values
  • evaluate the prepared statement
  • tidy up

The code looks something like this

// Database already opened
// All error checking omitted because I am lazy

sqlite3_stmt statement;
// Replace columns below with the names of your actual columns
// and key with the name of the primary key column
errorResult = sqlite3_prepare_v2(dbConnection, 
                                 "select columns from students where key = ?",
                                 -1,
                                 &statement,
                                 NULL);
// error check and handle any
errorResult = sqlite3_bind_int(statement, 1, 3); // Put 3 in place of first question mark
// error check and handle any
while ((errorResult = sqlite3_step(statement) == SQLITE_ROW)
{
    // Use sqlite3 column functions to get data 
    // http://www.sqlite.org/c3ref/column_blob.html
}
// error check and handle any
errorCheck = sqlite3_finalize(statement);
// error check and handle any

Upvotes: 1

Iqbal Khan
Iqbal Khan

Reputation: 4617

Run the select query, if it returns no record then the record does not exist.

Upvotes: 1

Related Questions