99热99这里只有精品6国产,亚洲中文字幕在线天天更新,在线观看亚洲精品国产福利片 ,久久久久综合网

歡迎加入QQ討論群258996829

SQL 數(shù)據(jù)庫抽象層 API 庫 Swift-Kuery

發(fā)布時間:2017-08-05 00:05  回復:0  查看:5323  感興趣:39  贊:1   最后回復:2017-08-05 00:05  
Swift-Kuery是一個可插拔的SQL數(shù)據(jù)庫驅動程序/ SDK抽象層。 其主要思想是提供一套API,能操作各種關系型數(shù)據(jù)庫,目前支持PostgreSQL、SQLite、MySQL。
雖然Swift-Kuery不是對象關系映射(ORM),但它為構建ORM提供了很大的基礎。 如果您不想使用特定的數(shù)據(jù)庫,允許在不同數(shù)據(jù)庫之間輕松切換, Swift-Kuery將會很有用。
示例代碼
PostgreSQL數(shù)據(jù)庫中有表格Grades,數(shù)據(jù)如下:
 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中創(chuàng)建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 數(shù)據(jù)庫
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.
  }
}


相關開源代碼

您還未登錄,請先登錄

熱門帖子

最新帖子

?