0

I'm using SQLite3 for the first time in my project. I've followed a couple of different tutorials and have managed to get everything working, apart from querying my table.

This is the code direct from one tutorial, Swift 3 which is outdated as the .fromCString doesn't exist:

let rowData = UnsafePointer<CChar>(sqlite3_column_text(dateStatement, 1))
            let finalString = String.fromCString(rowData)

This is my current code (with surrounding context) from an updated tutorial but still no luck.

    var dateStatement: OpaquePointer?
    let dateQuery = "SELECT * FROM StarLineTable"
    
    if sqlite3_prepare(db, dateQuery, -1, &dateStatement, nil) != SQLITE_OK {
        print("error preparing for search")
    }
    while sqlite3_step(dateStatement) == SQLITE_ROW {
       let rowData = sqlite3_column_text(dateStatement, 1)
        
        let finalString = String(cString: rowData)
        
        print(finalString)
        
    }

This gives: Value of optional type 'UnsafePointer?' must be unwrapped to a value of type 'UnsafePointer'

I'm probably missing something really simple - not even sure my question is correct as to what I need. Any help would be greatly appreciated!

  • Did you try `let finalString = String(cString: sqlite3_column_text(dateStatement, 1))` as suggested in the answer that I linked to? – Martin R Jun 28 '20 at 13:03
  • @MartinR I did, it allowed me to run my code but printed: �b �b �b ��2 ��2 �;l �� – Lizzy Brown Jun 28 '20 at 13:08
  • 1
    I have updated the other answer to show how to safely check the result from sqlite3_column_text() for a NULL pointer. – However what you describe in your last comment looks like a different problem. Are you sure that the column contains text and not binary data? – Martin R Jun 28 '20 at 13:11
  • @MartinR Think you're right in that it's a different problem. Just tried replacing the text field input with strings and something else is being printed. I assumed the weird output was due to conversion but doesn't look like it. I shall investigate. Thanks for the insight! – Lizzy Brown Jun 28 '20 at 13:20

0 Answers0