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

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.

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

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

Related

save file (.pdf) in database whit python 2.7

Craig Ringer Ican not work whit large object functions
My database looks like this
this is my table
-- Table: files
--
DROP TABLE files;
CREATE TABLE files
(
id serial NOT NULL,
orig_filename text NOT NULL,
file_data bytea NOT NULL,
CONSTRAINT files_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE files
I want save .pdf in my database, I saw you did the last answer, but using python27 (read the file and convert to a buffer object or use the large object functions)
I did the code would look like
path="D:/me/A/Res.pdf"
listaderuta = path.split("/")
longitud=len(listaderuta)
f = open(path,'rb')
f.read().__str__()
cursor = con.cursor()
cursor.execute("INSERT INTO files(id, orig_filename, file_data) VALUES (DEFAULT,%s,%s) RETURNING id", (listaderuta[longitud-1], f.read()))
but when I'm downloading, I save
fula = open("D:/INSTALL/pepe.pdf",'wb')
cursor.execute("SELECT file_data, orig_filename FROM files WHERE id = %s", (int(17),))
(file_data, orig_filename) = cursor.fetchone()
fula.write(file_data)
fula.close()
but when I'm downloading the file can not be opened, this damaged I repeat I can not work with large object functions
try this and turned me, can you help ?
I am thinking that psycopg2 Binary function does not user lob functions.
thus I used.....
path="salman.pdf"
f = open(path,'rb')
dat = f.read()
binary = psycopg2.Binary(dat)
cursor.execute("INSERT INTO files(id, file_data) VALUES ('1',%s)", (binary,))
conn.commit()
Just correction in INSERT statement, INSERT statement will be failed with null value in column "orig_filename" violates not-null constraint as orig_filename is defined as NOT NULL.... use instead
("INSERT INTO files(id, orig_filename,file_data) VALUES ('1','filename.pdf',%s)", (binary,))

sqlite3 update not working in ios

I am trying to update sqlite db. This is the code I am using
if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
const char * sql;
sql = "update tms set name = ?,place=?,stars=? where id=?";
sqlite3_stmt *selectStatement;
//prepare the select statement
int returnValue = sqlite3_prepare_v2(database, sql, -1, &selectStatement, NULL);
if(returnValue == SQLITE_OK)
{
sqlite3_bind_text(selectStatement, 1,[[payloadDict valueForKey:#"userName"] UTF8String] , [[payloadDict valueForKey:#"userName"] length],SQLITE_STATIC);
sqlite3_bind_text(selectStatement, 2,[[payloadDict valueForKey:#"locName"] UTF8String], [[payloadDict valueForKey:#"locName"] length],SQLITE_STATIC);
sqlite3_bind_int(selectStatement, 3, [[payloadDict valueForKey:#"starCount"] integerValue]);
sqlite3_bind_int(selectStatement, 4, [[payloadDict valueForKey:#"rowid"] integerValue]);
int success = sqlite3_step(selectStatement);
if(success == SQLITE_DONE)
{
isExist = TRUE;
}
else {
//NSAssert1(0,#"Error: Failed to Update %s",sqlite3_errmsg(database));
}
}
I am getting value 101 as success when sqlite3_step is executed. But database is not updated with new values.
How can I do this properly?
Thanks
I agree with #ott's excellent suggestion of making sure the database is located in the Documents directory (though I would have thought that that would have given you an error).
I'd also double check the value returned by [[payloadDict valueForKey:#"rowid"] integerValue] to make sure it matches a value in the id column for one of the existing rows in your table. If it doesn't match anything, sqlite3_step will return SQLITE_DONE even if nothing was updated.
Also note that you might also want to make sure that the id values are stored as numeric values, not text strings as sqlite is pretty lax about letting you store values in whatever data type you originally specified when you first inserted the data, regardless of how the table was defined), and I'm not sure if a WHERE clause looking for a numeric match will succeed if the data was originally stored as a text value. If you used an id column definition like id INTEGER PRIMARY KEY AUTOINCREMENT, where the system defined the values automatically for you, this isn't an issue, but if you manually populated the id column, it might be something to double check. (Generally it does a pretty good job in interpreting strings as numbers on the fly, but there are some weird situations that are problematic: For example, if you stored a string value of "5,127" in a numeric field, if you later then try to retrieve its numeric value, sqlite won't know what to do with the comma in the text value "5,127" and will interpret the numeric value as 5, not as 5127.)

How to insert DB Default values under EF?

when adding a new record like this
ContentContacts c2 = new ContentContacts();
c2.updated_user = c2.created_user = loggedUserId;
c2.created_date = c2.updated_date = DateTime.UtcNow;
db.ContentContacts.AddObject(c2);
I'm getting
Cannot insert the value NULL into column 'main_email_support', table 'SQL2008R2.dbo.ContentContacts'; column does not allow nulls. INSERT fails. The statement has been terminated.
but the default value in the database is an empty string like:
why am I getting such error? shouldn't the EF says something like:
"ohh, it's a nullvalue, so let's add the column default value instead"
I did a small test, created a table with a column that had a default value but did not allow nulls.
Then this SQL Statement:
INSERT INTO [Test].[dbo].[Table_1]
([TestText])
VALUES
(null)
Gives this error:
Msg 515, Level 16, State 2, Line 1
Cannot insert the value NULL into column 'TestText', table
'Test.dbo.Table_1'; column does not allow nulls. INSERT fails.
The problem here is that the insert specifies all the columns, also those with default values. The the Insert tries to update the columns with null values.
You have 2 options:
Update the table through a view, which does not contain the default columns
Set the default values in your C# code
A default value is business logic, so there is a case for it being set in the business layer of your application.

iPhone SQLite Database Reading And Writing

So I am trying to work with SQLite in one of iPhone applications and I am using the sqlite3 library. I am able to access the database and even make a query; in fact the query accesses the exact data but for some reason the string I am getting back is a long integer and not the string I was looking for. Here is the database and code:
Filename: Package.sql
Table Lessons
LessonID VARCHAR(64) Primary Key | LessonName VARCHAR(100) | EntryDate (DATETIME) | Chrono VARCHAR (20)
bfow02nso9xjdo40wksbfkekakoe29ak | Learning The History | 2010-08-05 16:24:35 | 0001
And the iPhone Code
...
-(NSString *)getRow:(NSString *)tablename where:(NSString *)column equals:(NSString *)value {
  const char *query = [[[[[[[#"SELECT * FROM `" stringByAppendingString:tablename] stringByAppendingString:#"` WHERE `"] stringByAppendingString:column] stringByAppendingString:#"` = '"] stringByAppendingString:value] stringByAppendingString:#"';"] cStringUsingEncoding:NSUTF8StringEncoding];
  NSString *result;
  if(sqlite3_open([dbpath UTF8String], &database) == SQLITE_OK) {
    sqlite3_stmt *compiledQuery;
    if(sqlite3_prepare_v2(database, query, -1, &compiledQuery, NULL) == SQLITE_OK) {
      while(sqlite3_step(compiledQuery) == SQLITE_ROW) {
        NSString *str_temp = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledQuery, 2)];
        result = str_temp;
        
      }
      sqlite3_finalize(compiledQuery);
    }
    sqlite3_close(database);
  }
 
  return result;
}
...
When the code executes:
CDatabase *db = [[CDatabase alloc]initWithDatabase:#"Package.sql"];
NSString *result = [db getRow:#"Lessons" where:#"Chrono" equals:#"0001"];
the returned value NSString *result has a value of "1,364,111". Why is it doing that??? It should be "Learning The History"
Are you sure that any of your SQLite calls are successful? You should initialize result to nil so that your function returns nil if any errors are caught.
Three (probably related) issues with your code:
The index to sqlite3_column_text should be zero-based; you're passing 2, which should refer to the third column. You probably mean to pass 1. From the docs:
...the second argument is the index of the column for which information should be returned. The leftmost column of the result set has the index 0.
You really shouldn't use SELECT *. Specify the columns you want!
You should specialize your query by binding values, not by concatenating strings! Your code is rife with the possibility of SQL injections (not to mention incorrect queries).
For example (with no error checking):
const char *query = "SELECT * FROM ? WHERE ?=?";
sqlite3_stmt *compiledQuery;
sqlite3_prepare_v2(database, query, -1, &compiledQuery, NULL);
sqlite3_bind_text(compiledQuery, 1, "Lessons", -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledQuery, 2, "Chrono", -1, SQLITE_TRANSIENT);
sqlite3_bind_text(compiledQuery, 3, "0001", -1, SQLITE_TRANSIENT);
Note that the index here is 1-based (I don't know why they do that). From the docs:
The second argument is the index of the SQL parameter to be set. The leftmost SQL parameter has an index of 1.
Haha whoops I realized that I was just displaying the string as a data format by using the %d string format. when i changed it to %# i got the string format

How to append an integer to a const char value in iPhone?

I have SQL query statement which used to display the contents in the table. The SQL statement consist of a where clause which is to be appended with numeric value as 1 ,2 3 etc depends upon the previously selected content. I am having the numeric value as int and I want it to append to SQL statement which is const char. How can I append both the values?
My query is:
select * from Book where id=1;
I have the id value is integer
You simply bind the parameter. E.g.:
sqlite3 *db;
... // open database
sqlite3_stmt *pStmt;
sqlite3_prepare_v2(
db,
"select * from book where id = ?",
-1,
&pStmt,
NULL
);
sqlite3_bind_int(pStmt, 1, bookId);
See the SQLite documentation on compiling and binding prepared statements. You can reuse the same statement more than once. sqlite3_clear_bindings lets you reset the values.
Is this what you're looking for?
NSString* result = [NSString stringWithFormat:#"SELECT * FROM Book WHERE id=%d", myInt];
to compose your SQL string?