您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 中 sqlite3 常用指令整理

編輯:iOS 開發綜合

聲明:以下指令並非每條都實際跑過,僅作為語法收藏與查閱之用,歡迎指正其中的錯誤。

查表是否存在與讀取建表語法

SELECT count(*) FROM sqlite_master WHERE type="table" AND name = "table_name"
// 從 sqlite_master 這個系統表中查找名為 "table_name" 的表的數量。
// 沒錯,是數量,所以如果結果大於 0,說明這個表存在。

SELECT name, sql FROM sqlite_master WHERE type="table" AND name = "table_name"
// 據說可以返回創建 "table_name" 的語句,當然也包含每個欄位名。

select * from "table_name", [rs columnNameForIndex:i]
// rs 是返回的結果集,該語句返回 index == i 的欄位名。

建立資料表

CREATE TABLE "table_name" (first_col integer)
// 建立資料表。

CREATE TABLE "table_name" (first_col integer DEFAULT 0, second_col varchar DEFAULT 'hello')
// 建立資料表,first_col 欄位有缺省值。

CREATE TABLE IF NOT EXISTS "table_name" (first_col integer)
// 若 "table_name" 已存在會產生衝突、導致語句失敗,IF NOT EXISTS 可避免這種錯誤。

CREATE TABLE "table_name2" AS SELECT * FROM "table_name1";
// 依 table_name1 的結構建立 table_name2,但不包含主鍵約束與缺省值。
// 使用 .schema "table_name2" 可返回建立資料表的語句。

各種欄位約束

CREATE TABLE "table_name" (first_col integer PRIMARY KEY ASC);   // 主鍵約束
CREATE TABLE "table_name" (first_col integer UNIQUE);            // 欄位值唯一性約束
CREATE TABLE "table_name" (first_col integer NOT NULL);          // 禁止為 NULL
CREATE TABLE "table_name" (first_col integer CHECK (first_col < 5)); // 欄位值範圍約束

修改與刪除

ALTER TABLE "table_name1" RENAME TO "table_name2";        // 重新命名資料表
ALTER TABLE "table_name" ADD COLUMN second_col integer;   // 為資料表新增欄位
DROP TABLE "table_name";                                  // 刪除資料表
DROP TABLE IF EXISTS "table_name";                        // 刪除不存在的表會出錯,用 IF EXISTS 避免

視圖

CREATE VIEW "table_name" AS SELECT * FROM "table_name" WHERE first_col > 100;  // 建立視圖
DROP VIEW IF EXISTS "view_name";                                              // 刪除視圖

附加其他資料庫

ATTACH DATABASE 'd:/mydb.db' AS mydb   // 當前連線附加 "d:/mydb.db",之後的操作都在該庫下生效
.exit                                   // 退出當前資料庫

以上指令涵蓋了 sqlite3 在 iOS 開發中最常翻查的幾類操作:判斷表是否存在、讀取建表語法、建立與修改資料表、加上各類約束,以及視圖的建立與刪除。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved