Swift-Kuery是一个可插拔的SQL数据库驱动程序/ SDK抽象层。 其主要思想是提供一套API,能操作各种关系型数据库,目前支持PostgreSQL、SQLite、MySQL。
虽然Swift-Kuery不是对象关系映射(ORM),但它为构建ORM提供了很大的基础。 如果您不想使用特定的数据库,允许在不同数据库之间轻松切换,
Swift-Kuery将会很有用。
示例代码
PostgreSQL数据库中有表格Grades,数据如下:
id | course | grade
------+-----------+-------
12345 | physics | 82
12345 | chemistry | 90
12345 | history | 98
78901 | history | 100
78901 | chemistry | 94
78901 | physics | 90
24680 | physics | 74
24680 | chemistry | 92
24680 | history | 90
在Swift中创建Grades类,继承Table。
import SwiftKuery
import SwiftKueryPostgreSQL
class Grades: Table {
let tableName = "Grades"
let id = Column("id")
let course = Column("course")
let grade = Column("grade")
}
let grades = Grades()
连接PostgreSQL 数据库
let pool = PostgreSQLConnection.createPool(host: "localhost", port: 5432, options: [.userName("username"), .password("password")], poolOptions: ConnectionPoolOptions(initialCapacity: 10, maxCapacity: 50, timeout: 10000)))
if let connection = pool.getConnection() {
// Build and execute your query here.
}
else {
print("Error: failed to get a connection.")
}
用SQL查询方式如下:
SELECT course, ROUND(AVG(grade), 1) AS "average" FROM grades
GROUP BY course
HAVING AVG(grade) > 90
ORDER BY AVG(grade) ASC
使用Swift-Kuery方式:
let query = Select(grades.course, round(avg(grades.grade), to: 1).as("average"), from: grades)
.group(by: grades.course)
.having(avg(grades.grade) > 90)
.order(by: .ASC(avg(grades.grade)))
guard let connection = pool.getConnection() else {
// Error
}
connection.execute(query: query) { result: QueryResult in
if let resultSet = queryResult.asResultSet {
for title in resultSet.titles {
// The column names of the result.
}
for row in resultSet.rows {
for value in row {
...
}
}
}
else if let queryError = result.asError {
// Something went wrong.
}
}