我刚刚学习 SQLite.swift 并正在阅读它的文档。我正在尝试查询我已经拥有但不知道如何执行此操作的现有表。在文档中,它展示了如何查询创建的表(如下所示https://github.com/stephencelis/SQLite.swift/blob/master/Documentation/Index.md#selecting-rows)
let users = Table("users")
try db.run(users.create { t in // CREATE TABLE "users" (
t.column(id, primaryKey: true) // "id" INTEGER PRIMARY KEY NOT NULL,
t.column(email, unique: true) // "email" TEXT UNIQUE NOT NULL,
t.column(name) // "name" TEXT
})
// )
for user in try db.prepare(users) {
print("id: \(user[id]), email: \(user[email]), name: \(user[name])")
// id: 1, email: [email protected], name: Optional("Alice")
}
// SELECT * FROM "users"
我有一个可以连接到它的现有表,但我能够从中获取信息的唯一方法是通过执行 db.scalar 但不确定这是否是正确的方法。
let home = FileManager.default.homeDirectoryForCurrentUser
let dbURL = "Desktop/MyPracticeCode/EpubParser/"
let myPath = home.appendingPathComponent(dbURL)
let db = try Connection("\(myPath)/TestTable.sqlite3")
print(db.scalar("SELECT WtName FROM MyTable"))
这会打印出我需要的数据,但不确定这是否是正确的方法。有没有一种方法可以将我现有的表分配给“表”类型并像在示例中那样进行查询。我在网上到处搜索但找不到明确的答案。谢谢
我设法找出答案。如果有人遇到这个问题或同样的问题,这就是我设法解决的方法。仍然不确定这是否是正确的方法。基本上,您需要像示例中那样使用列重新创建表,但使用列的名称。创建一个表并将其命名为与数据库中的表完全相同的名称。下面是我的做法
let id = Expression<Int64>("id")
let Article = Expression<String?>("Article")
let ArticleName = Expression<String?>("ArticleName")
let ImageThumbnail = Expression<String?>("ImageThumbnail")
let WtCoverImage = Expression<String?>("WtCoverImage")
let myTable = Table("MyTable")
try db.run(myTable.create(ifNotExists: true){ t in
t.column(id,primaryKey: true)
t.column(Article)
t.column(ArticleName)
t.column(ImageThumbnail)
t.column(WtCoverImage)
})
这是我使用的:
try db.run(users.create(ifNotExists: true) { t in /* ... */ })
// CREATE TABLE "users" IF NOT EXISTS -- ...
现在我可以像这样查询了
for myData in try db.prepare(myTable){
print("WtCoverImage\(myData[WtCoverImage])")
}
class SqliteDB{
static let shared:SqliteDB = SqliteDB()
private init(){}
var DB:Connection!
/// path for creat a databased file.
func createDBPath(){
do {
let dbPath = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("chatDB.sqlite").path
DB = try Connection(dbPath)
print(dbPath)
} catch {
print(error.localizedDescription)
}
}
func dbTables_ChatMessage(){
let tableQuery = """
CREATE TABLE IF NOT EXISTS message_list (id INTEGER, conversation_id INTEGER UNIQUE, conversation_recipient_id INTEGER, timestamp INTEGER UNIQUE, content_type TEXT, message TEXT, user_id INTEGER, user_name TEXT, group_id INTEGER,isOnline TEXT,room_id INTEGER, local_conversation_id INTEGER ,room_unique_id TEXT,PRIMARY KEY(id AUTOINCREMENT))
"""
do {
try DB.run(tableQuery)
} catch {
print(error.localizedDescription)
}
}
}
我的解决方案使其工作,而无需根据 Nbera 的答案创建新数据库。
并关注...
let seededDataUrl = Bundle.main.url(forResource: "dataBase", withExtension: "db")
db = try Connection(seededDataUrl!.path())
for myData in try db.prepare(myTable){
print("WtCoverImage\(myData[WtCoverImage])")
}
享受