swift创建一个表里面有图片和两个文本
时间: 2024-05-03 14:19:40 浏览: 253
Swifter - 100 个 Swift 必备 tips(第二版 免费下载)
5星 · 资源好评率100%
您可以使用SQLite数据库来创建一个表格,并将图片和文本存储在其中。以下是一个示例代码:
```swift
import Foundation
import SQLite3
import UIKit
class MyDatabase {
var db: OpaquePointer?
func createTable() {
let fileUrl = try!
FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false).appendingPathComponent("myDatabase.sqlite")
if sqlite3_open(fileUrl.path, &db) != SQLITE_OK {
print("Error opening database")
return
}
let createTableQuery = "CREATE TABLE IF NOT EXISTS myTable (id INTEGER PRIMARY KEY AUTOINCREMENT, image BLOB, title TEXT, description TEXT)"
if sqlite3_exec(db, createTableQuery, nil, nil, nil) != SQLITE_OK{
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("Error creating table: \(errmsg)")
return
}
}
func insertData(image: UIImage?, title: String, description: String) {
let imageData = image?.jpegData(compressionQuality: 0.5)
var stmt: OpaquePointer?
let insertQuery = "INSERT INTO myTable (image, title, description) VALUES (?, ?, ?)"
if sqlite3_prepare(db, insertQuery, -1, &stmt, nil) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("Error preparing insert statement: \(errmsg)")
return
}
sqlite3_bind_blob(stmt, 1, imageData?.bytes, Int32(imageData?.count ?? 0), nil)
sqlite3_bind_text(stmt, 2, title, -1, nil)
sqlite3_bind_text(stmt, 3, description, -1, nil)
if sqlite3_step(stmt) != SQLITE_DONE {
let errmsg = String(cString: sqlite3_errmsg(db)!)
print("Error inserting data into table: \(errmsg)")
return
}
sqlite3_finalize(stmt)
}
}
```
使用上述代码,您可以创建一个名为“myTable”的表格,并在其中插入包含图像、标题和描述的行。
请注意,此代码仅提供了SQLite数据库的基础知识,并且在实际应用中可能需要进行更多的优化和错误处理。
阅读全文