Wrong write to Sqlite database

Hi guys, please help me with sqlite database. When I save the data in the table, it always saves the wrong data in the columns. They don't match the submitted data at all. I don't know where I am making a mistake. Thank you!

Answered by endecotp in 780988022

I think the issue is related to the lifetime of the strings. Try changing

sqlite3_bind_text(insertStatement, sqlite3_bind_parameter_index(insertStatement, ":name"), name, -1, nil)

etc. to

sqlite3_bind_text(insertStatement, sqlite3_bind_parameter_index(insertStatement, ":name"), name, -1, SQLITE_TRANSIENT)

Re String(describing: …), isn’t it sufficient to have the String(cStirng: …)? Why have you wrapped that in describing: ? That seems unnecessary / unhelpful to me, but maybe I have missed something.

The first thing you should do is to check if the problem is during the INSERT or the SELECT. Inspect your sqlite file with e.g. the sqlite command line program and see if the data is correct in the file.

Why are you using String(describing: …) ?

1.The problem is in the "insert" it is visible in the console, because the ViewController sends the correct data to the DatabaseManager , which it prints in the console and then saves before saving to the table. But in the database it saves wrong as you can see in the screenshot. 2.I don't understand the question, what should I use?

Accepted Answer

I think the issue is related to the lifetime of the strings. Try changing

sqlite3_bind_text(insertStatement, sqlite3_bind_parameter_index(insertStatement, ":name"), name, -1, nil)

etc. to

sqlite3_bind_text(insertStatement, sqlite3_bind_parameter_index(insertStatement, ":name"), name, -1, SQLITE_TRANSIENT)

Re String(describing: …), isn’t it sufficient to have the String(cStirng: …)? Why have you wrapped that in describing: ? That seems unnecessary / unhelpful to me, but maybe I have missed something.

Yes! I changed the code: sqlite3_bind_text(insertStatement, sqlite3_bind_parameter_index(insertStatement, ":name"), name, -1, SQLITE_TRANSIENT) and added: let SQLITE_TRANSIENT = unsafeBitCast(-1, to: sqlite3_destructor_type.self) Thank you!

Wrong write to Sqlite database
 
 
Q