iosswiftsqlitefmdb

iOS Swift insert into sqlite FMDB


here is my issue : I have this wine app, that shows the content of my database to the user in a nice tableview. I can get data from it quite easily, using the FMDB executeQuery function, but whenever I try to add something to the SQLite table, it just fails.

Here is the code I use.

do
 {
     try sharedInstance.database!.executeUpdate("INSERT INTO wine VALUES (?, ?, ?)", values: [id, name, wineType])
 }
 catch
 {
     print("error \(error)")
 }

I've tried putting everything in one string, and then send it as the first parameter, and putting nil as a second parameter, and that also fails. This syntax comes from the Data Sanitisation section in the FMDB README from github

I've found a few similar cases, but the answers were Objective-C. Please note that I am completely new to iOS, I don't know anything about Objective-C, and this is my first Swift app.

What am I doing wrong ?


Solution

  • In some cases executeUpdate it fails so First try to use executeQuery or executeStatmentsto fix the issue.

    If it didn't work, In my opinion the proper way for executing sql statement after opening database is:

    executeUpdate("INSERT INTO wine VALUES ('\(id)', '\(name)', '\(wineType)')")
    

    And close database after the statement is successfully executed. What is the type of your id in database ? And is it auto increment ?

    What error are you getting in the console ? try to use breakpoint and see whats happening.

    Update The previous code is not preferred to use on production environment since it’s subject to SQL injection Reference , in my opinion using FMDB with iOS and the previous code is just ok to use.