从FMDB数据库中获取数据

时间:2016-08-24 05:02:46

标签: ios swift fmdb

在我的应用程序中,我想从FMDB数据库中获取数据以及我想发送给观看的数据。但问题是,当获取数据时,它不会在控制台中显示实际数据,如ticket_type = Movie,time = 11:42 p.m.相反,它只显示内存地址结果。

我的TicketData的源代码在

之下
class TicketData: NSObject {
var field1: String?
var field2: String?
var field3: String?
var field4: String?

override init() {
    super.init()
}

convenience init(field1: String, field2: String, field3: String, field4: String) {
   self.init()

        self.field1 = field1
        self.field2 = field2
        self.field3 = field3
        self.field4 = field4

}

}

我的应用的截图是 我的应用的截图 image

我的源代码在

之下
class TicketDetailViewController: UIViewController, WCSessionDelegate {

var databasePath = NSString()
var holding_Ticket_category: String = ""
var holding_Image: UIImage?
var hold_ticketName: String = ""
var hold_ticketDate: String = ""
var hold_ticketTime: String = ""
var session: WCSession!
var ticketDataArray:[TicketData] = []


@IBOutlet weak var ticket_grey: UIImageView!
@IBOutlet weak var cropped_frame: UIImageView!
@IBOutlet weak var display_image: UIImageView!
@IBOutlet weak var ticket_type_name: UILabel!
@IBOutlet weak var ticket_date: UILabel!
@IBOutlet weak var ticket_time: UILabel!
@IBOutlet weak var ticket_category: UILabel!


override func viewDidLoad()
{
    super.viewDidLoad()

    if WCSession.isSupported(){
        self.session  = WCSession.defaultSession()
        self.session.delegate = self
        self.session.activateSession()
    }

    display_image.image = holding_Image
    ticket_type_name.text = hold_ticketName
    ticket_date.text = hold_ticketDate
    ticket_time.text = hold_ticketTime
    ticket_category.text = holding_Ticket_category

    let filemgr =  NSFileManager.defaultManager()
    let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let docsDir = dirPaths[0]
    var ticketDB: FMDatabase

    databasePath = (docsDir as NSString).stringByAppendingPathComponent("ticket_Pass.sqlite")


    if !filemgr.fileExistsAtPath(databasePath as String)
    {

        ticketDB = FMDatabase(path: databasePath as String)
        if ticketDB.open()
        {

            let sql_stmt = "CREATE TABLE IF NOT EXISTS TICKET (ID INTEGER PRIMARY KEY AUTOINCREMENT, IMAGE TEXT, TICKET_CATEGORY TEXT, TICKET_TYPE TEXT, DATE TEXT, TIME TEXT)"
            if !ticketDB.executeStatements(sql_stmt)
            {
                print("Error: \(ticketDB.lastErrorMessage())")
            }
            ticketDB.close()
        } else
        {

            print("Error: \(ticketDB.lastErrorMessage())")
        }
    }
}

@IBAction func addTickets(sender:UIButton)   {

    let ticketDB = FMDatabase(path: databasePath as String)
    if ticketDB.open()
    {

            let insertSQL = "INSERT INTO TICKET (image, ticket_category, ticket_type, date, time) VALUES ('\(display_image.image!)', '\(ticket_category.text!)', '\(ticket_type_name.text!)', '\(ticket_date.text!)', '\(ticket_time.text!)')"

            let result = ticketDB.executeUpdate(insertSQL,withArgumentsInArray: nil)

            if !result
            {

                print("Error: \(ticketDB.lastErrorMessage())")

            } else
            {

                let alt = PMAlertController(title: "Success!", description: "Your data is saved to Database!", image: UIImage(named: ""), style: .Alert)

                alt.addAction(PMAlertAction(title: "OK!", style: .Default, action: { (ACTION) -> Void in

                         self.navigationController?.popToRootViewControllerAnimated(true)

                }))

                        self.presentViewController(alt, animated: true, completion: nil)
                        print(databasePath)


           }
    }
}


@IBAction func deleteTickets(sender: UIButton) {
    let alt = PMAlertController(title: "Delete Ticket Details!", description: "Are you sure?", image: UIImage(named: ""), style: .Alert)

    alt.addAction(PMAlertAction(title: "Cancel", style: PMAlertActionStyle.Default, action: { (ACTION) -> Void in

        self.dismissViewControllerAnimated(true, completion: nil)

    }))
    alt.addAction(PMAlertAction(title: "OK", style: PMAlertActionStyle.Default, action: { (ACTION) -> Void in

        self.navigationController?.popToRootViewControllerAnimated(true)
    }))
    self.presentViewController(alt, animated: true, completion: nil)
}


@IBAction func sendToWatch(sender: AnyObject) {


    let ticketDB = FMDatabase(path: databasePath as String)
    if ticketDB.open()
    {

        let insertSQL = "INSERT INTO TICKET (image, ticket_category, ticket_type, date, time) VALUES ('\(display_image.image!)', '\(ticket_category.text!)', '\(ticket_type_name.text!)', '\(ticket_date.text!)', '\(ticket_time.text!)')"

        let result = ticketDB.executeUpdate(insertSQL,withArgumentsInArray: nil)

        if !result
        {

            print("Error: \(ticketDB.lastErrorMessage())")

        } else
        {

            let alt = PMAlertController(title: "Success!", description: "Your data is saved to Database!", image: UIImage(named: ""), style: .Alert)

            alt.addAction(PMAlertAction(title: "OK!", style: .Default, action:
                { (ACTION) -> Void in

                    let ticketDB = FMDatabase(path: self.databasePath as String)
                    if ticketDB.open()
                    {

                        let querySQL = "SELECT * FROM TICKET"

                        let result: FMResultSet? = ticketDB.executeQuery(querySQL, withArgumentsInArray: nil)

                        if let result = result
                        {

                           var ticketData = TicketData()
                            while (result.next() == true)
                            {
                                let image = result.stringForColumn("image")
                                let ticket_category = result.stringForColumn("ticket_category")
                                let ticket_type = result.stringForColumn("ticket_type")
                                let date = result.stringForColumn("date")
                                let time = result.stringForColumn("time")
                                ticketData = TicketData(field1: ticket_category!, field2: ticket_type!, field3: date!, field4: time!, field5: image!)
                                 self.ticketDataArray.append(ticketData)


                            }
                        print("Data: \(result.resultDictionary())")


                            }


                       }else
                       {
                            print("Error: \(ticketDB.lastErrorMessage())")

                       }

                    ticketDB.close()


                    }

            }))

            self.presentViewController(alt, animated: true, completion: nil)
            print(databasePath)

        }
    }

1 个答案:

答案 0 :(得分:1)

ticketData是一个对象,您正在尝试使用

打印对象
print("Data: \(ticketData)")

每当我们尝试打印对象时,始终会打印对象的内存地址而不是对象的属性。如果要打印对象属性,请逐个打印,如

print("Data: \(ticketData.ticket_type)")

等等。如果你想一次打印所有东西,你可以做的是你可以从resultSet中获取一个字典对象并打印出来。

print("Data:\(resultSet.resultDictionary())")

编辑:如何获取结果集的最后一个值。

if let result = result {

var ticketData = TicketData()
var latestTicketDict = [String: AnyObject]()

while (result.next() == true) {
    let image = result.stringForColumn("image")
    let ticket_category = result.stringForColumn("ticket_category")
    let ticket_type = result.stringForColumn("ticket_type")
    let date = result.stringForColumn("date")
    let time = result.stringForColumn("time")
    ticketData = TicketData(field1: ticket_category!, field2: ticket_type!, field3: date!, field4: time!, field5: image!)
    self.ticketDataArray.append(ticketData)
    latestTicketDict = result.resultDictionary()
}

print("Data: \(latestTicketDict)")

}

更新:另外,我建议您浏览github页面上的FMDB文档,学习FMDB上的一些教程,以编写更高效的数据库操作。也不要关闭数据库并为每个数据库操作打开数据库,因为FMDB的创建者说When to close SQLite database (using FMDB) -

  

"除非您更改架构,否则请将其保持打开状态。这是唯一的原因   关闭它,并不断重新打开它对性能有点打击   /电池寿命。"

另外,我建议你看一下FMDatabaseQueue。

希望这有助于。