简体   繁体   中英

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 ?

The syntax is correct, may be you want to check if:

  • you called sharedInstance.database!.open() beforehand
  • your table only consist of 3 columns

If you include FMDatabaseAdditionsVariadic.swift and FMDatabaseVariadic.swift into your project, you can call executeUpdate like this:

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

Note :- Here i sending you code for Insert record in Database using FMDB in swift.

import UIKit

class FMDBDatabaseSignUpVC: UIViewController {

@IBOutlet weak var txtFirstNameOutlet: UITextField!
@IBOutlet weak var txtLastNameOutlet: UITextField!
@IBOutlet weak var txtEMailIDOutlet: UITextField!
@IBOutlet weak var txtPasswordOutlet: UITextField!

var databasePath = NSString()
override func viewDidLoad() {
    super.viewDidLoad()

    let filemgr = NSFileManager.defaultManager()
    let dirPaths =
        NSSearchPathForDirectoriesInDomains(.DocumentDirectory,
                                            .UserDomainMask, true).first as String!

    databasePath = (dirPaths as NSString).stringByAppendingPathComponent("swiftDemo.db")

    if !filemgr.fileExistsAtPath(databasePath as String)  {
        let contactDB = FMDatabase (path: databasePath as String)
        if contactDB == nil {
            print(contactDB.lastErrorMessage())
        }
    }
    // Do any additional setup after loading the view.
}

@IBAction func btnSaveAction(sender: UIButton) {

    let contactDB = FMDatabase (path: databasePath as String)
    if contactDB.open() {
        let InsertQry = "insert into userInfo (userFirstName, userLastName,userEmailID,userPassword) values ('\(txtFirstNameOutlet.text!)','\(txtLastNameOutlet.text!)','\(txtEMailIDOutlet.text!)','\(txtPasswordOutlet.text!)')"
        let result = contactDB.executeUpdate(InsertQry, withArgumentsInArray: nil)
        if !result {
            print(contactDB.lastErrorMessage())
        }
        else
        {
            print("Success")
            txtFirstNameOutlet.text=""
            txtLastNameOutlet.text=""
            txtEMailIDOutlet.text=""
            txtPasswordOutlet.text=""
        }
    }
}
}

In some cases executeUpdate it fails so First try to use executeQuery or executeStatments to 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.

This should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM