Search code examples
iosswiftsqlitefmdb

How to retrieve the data using query statement in Swift?


I want to retrieve the data from my table named cache_image, but I am not sure how to do that and I am facing an error here.

func checkCachedImages() ->Bool{
    database?.open()
    var count = Int()
    for i in images{
        do{
            if let value = database?.executeQuery("SELECT DOWNLOAD_URL FROM CACHED_IMAGE WHERE IMAGE_NAME = ?", withArgumentsIn: [i]){
                while value.next(){
                    print(value.string(forColumn: "IMAGE_NAME"))
                    print(value.string(forColumn: "DOWNLOAD_URL"))
                    count += 1
                    print(count)
                }
            }
        }catch {
            print(error)
        }
    }
    database?.close()
    if count == images.count{
        print("The count is \(count)")
        return true
    }

    return false
}

I do have a table named cached_image and two columns named image_name and download_url but when i try to access that using

print(value.string(forColumn: "IMAGE_NAME")

it is displaying warning :

Couldn't find image_name and for column "download_url", it is showing "Optional("")"

Please help me to solve this issue.


Solution

  • You can't read image_name from the result since it isn't part of the SELECT clause but you don't need it since you can get it from i

    var numberOfRows = 0
    var urls: [String] = ()
    print("Image name: \(i)")
    if let result = try database?.executeQuery("SELECT download_url FROM CACHED_IMAGE WHERE IMAGE_NAME = ?", values: [i]) {
        while result.next() {
            numberOfRows += 1
            let url = result.stringForColumnIndex(0)
            urls.append(url)
            print("\(url), \(i)")
        }
    }
    print(numberOfRows)