建立及修改資料庫

Adobe AIR 1.0 以及更新的版本

在您的應用程式能夠新增或擷取資料以前,必須在應用程式中定義您應用程式能夠存取的資料庫。本節描述建立資料庫及在資料庫中建立資料結構的工作。雖然這些工作的使用程度不如資料偵聽和擷取那麼頻繁,但是大部分應用程式都需要執行這些工作。

建立資料庫

若要建立資料庫檔案,首先要建立 SQLConnection 實體。然後呼叫其 open() 方法,在同步執行模式中開啟,或呼叫其 openAsync() 方法在非同步執行模式中開啟。open()openAsync() 方法都可用來開啟資料庫的連線。如果您傳遞 File 實體來參考沒有 reference 參數 (第一個參數) 的檔案位置,open()openAsync() 方法在會該檔案位置建立資料庫檔案,然後開啟新建立資料庫的連線。

不管是呼叫 open() 方法或 openAsync() 方法來呼叫資料庫,資料庫檔案的名稱都可以是任何有效的檔案名稱加上任何副檔名。如果您呼叫 open()openAsync() 方法,而 reference 參數為 null,就會建立新的記憶體內資料庫,而不是在硬碟上建立資料庫檔案。

下面列出的程式碼會示範使用非同步執行模式來建立資料庫檔案 (新資料庫) 的程序。在此情況下,資料庫檔案會儲存於指向應用程式儲存目錄中,檔案名稱是「DBSample.db」:

import flash.data.SQLConnection; 
import flash.events.SQLErrorEvent; 
import flash.events.SQLEvent; 
import flash.filesystem.File; 
     
var conn:SQLConnection = new SQLConnection(); 
     
conn.addEventListener(SQLEvent.OPEN, openHandler); 
conn.addEventListener(SQLErrorEvent.ERROR, errorHandler); 
     
// The database file is in the application storage directory 
var folder:File = File.applicationStorageDirectory; 
var dbFile:File = folder.resolvePath("DBSample.db"); 
     
conn.openAsync(dbFile); 
     
function openHandler(event:SQLEvent):void 
{ 
    trace("the database was created successfully"); 
} 
     
function errorHandler(event:SQLErrorEvent):void 
{ 
    trace("Error message:", event.error.message); 
    trace("Details:", event.error.details); 
} 
<?xml version="1.0" encoding="utf-8"?> 
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()"> 
    <mx:Script> 
        <![CDATA[ 
            import flash.data.SQLConnection; 
            import flash.events.SQLErrorEvent; 
            import flash.events.SQLEvent; 
            import flash.filesystem.File; 
             
            private function init():void 
            { 
                var conn:SQLConnection = new SQLConnection(); 
                 
                conn.addEventListener(SQLEvent.OPEN, openHandler); 
                conn.addEventListener(SQLErrorEvent.ERROR, errorHandler); 
                  
                // The database file is in the application storage directory 
                var folder:File = File.applicationStorageDirectory; 
                var dbFile:File = folder.resolvePath("DBSample.db"); 
                 
                conn.openAsync(dbFile); 
            } 
             
            private function openHandler(event:SQLEvent):void 
            { 
                trace("the database was created successfully"); 
            } 
             
            private function errorHandler(event:SQLErrorEvent):void 
            { 
                trace("Error message:", event.error.message); 
                trace("Details:", event.error.details); 
            } 
        ]]> 
    </mx:Script> 
</mx:WindowedApplication>
備註: 雖然 File 類別可讓您指向特定原生檔案路徑,但這麼做會讓應用程式無法跨平台使用。例如,C:\Documents and Settings\joe\test.db 這個路徑僅適用於 Windows。因此,最好使用 File 類別的靜態屬性,如 File.applicationStorageDirectory,和 resolvePath() 方法 (如上一個範例所示)。 如需詳細資訊,請參閱 File 物件的路徑

若要以同步方式執行作業,當您使用 SQLConnection 實體開啟資料庫連線,請呼叫 open() 方法。下列範例會示範如何建立及開啟會以同步方式執行其作業的 SQLConnection 實體:

import flash.data.SQLConnection; 
import flash.errors.SQLError; 
import flash.filesystem.File; 
     
var conn:SQLConnection = new SQLConnection(); 
     
// The database file is in the application storage directory 
var folder:File = File.applicationStorageDirectory; 
var dbFile:File = folder.resolvePath("DBSample.db"); 
     
try 
{ 
    conn.open(dbFile); 
    trace("the database was created successfully"); 
} 
catch (error:SQLError) 
{ 
    trace("Error message:", error.message); 
    trace("Details:", error.details); 
} 
<?xml version="1.0" encoding="utf-8"?> 
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()"> 
    <mx:Script> 
        <![CDATA[ 
            import flash.data.SQLConnection; 
            import flash.errors.SQLError; 
            import flash.filesystem.File; 
             
            private function init():void 
            { 
                var conn:SQLConnection = new SQLConnection(); 
                 
                // The database file is in the application storage directory 
                var folder:File = File.applicationStorageDirectory; 
                var dbFile:File = folder.resolvePath("DBSample.db"); 
                  
                try 
                { 
                    conn.open(dbFile); 
                    trace("the database was created successfully"); 
                } 
                catch (error:SQLError) 
                { 
                    trace("Error message:", error.message); 
                    trace("Details:", error.details); 
                } 
            } 
        ]]> 
    </mx:Script> 
</mx:WindowedApplication>

建立資料庫資料表

在資料庫中建立資料表包含在該資料庫上執行 SQL 陳述式、使用與用來執行 SELECTINSERT 之類 SQL 陳述式相同的處理等等。若要建立資料表,請使用 CREATE TABLE 陳述式,該陳述式包含了欄的定義和新資料表的限制。如需有關執行 SQL 陳述式的詳細資訊,請參閱使用 SQL 陳述式

下列範例會示範如何使用非同步執行模式,在現有資料庫檔案中建立名為「employees」的資料表。請注意,此程式碼會假設已有一個實體化且連線至資料庫的 SQLConnection 實體 conn

import flash.data.SQLConnection; 
import flash.data.SQLStatement; 
import flash.events.SQLErrorEvent; 
import flash.events.SQLEvent; 
     
// ... create and open the SQLConnection instance named conn ... 
     
var createStmt:SQLStatement = new SQLStatement(); 
createStmt.sqlConnection = conn; 
     
var sql:String =  
    "CREATE TABLE IF NOT EXISTS employees (" +  
    "    empId INTEGER PRIMARY KEY AUTOINCREMENT, " +  
    "    firstName TEXT, " +  
    "    lastName TEXT, " +  
    "    salary NUMERIC CHECK (salary > 0)" +  
    ")"; 
createStmt.text = sql; 
     
createStmt.addEventListener(SQLEvent.RESULT, createResult); 
createStmt.addEventListener(SQLErrorEvent.ERROR, createError); 
     
createStmt.execute(); 
     
function createResult(event:SQLEvent):void 
{ 
    trace("Table created"); 
} 
     
function createError(event:SQLErrorEvent):void 
{ 
    trace("Error message:", event.error.message); 
    trace("Details:", event.error.details); 
}
<?xml version="1.0" encoding="utf-8"?> 
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()"> 
    <mx:Script> 
        <![CDATA[ 
            import flash.data.SQLConnection; 
            import flash.data.SQLStatement; 
            import flash.events.SQLErrorEvent; 
            import flash.events.SQLEvent; 
             
            private function init():void 
            { 
                // ... create and open the SQLConnection instance named conn ... 
                 
                var createStmt:SQLStatement = new SQLStatement(); 
                createStmt.sqlConnection = conn; 
                 
                var sql:String =  
                    "CREATE TABLE IF NOT EXISTS employees (" +  
                    "    empId INTEGER PRIMARY KEY AUTOINCREMENT, " +  
                    "    firstName TEXT, " +  
                    "    lastName TEXT, " +  
                    "    salary NUMERIC CHECK (salary > 0)" +  
                    ")"; 
                createStmt.text = sql; 
                 
                createStmt.addEventListener(SQLEvent.RESULT, createResult); 
                createStmt.addEventListener(SQLErrorEvent.ERROR, createError); 
                 
                createStmt.execute(); 
            } 
             
            private function createResult(event:SQLEvent):void 
            { 
                trace("Table created"); 
            } 
             
            private function createError(event:SQLErrorEvent):void 
            { 
                trace("Error message:", event.error.message); 
                trace("Details:", event.error.details); 
            } 
        ]]> 
    </mx:Script> 
</mx:WindowedApplication>

下列範例會示範如何使用同步執行模式,在現有資料庫檔案中建立名為「employees」的資料表。請注意,此程式碼會假設已有一個實體化且連線至資料庫的 SQLConnection 實體 conn

import flash.data.SQLConnection; 
import flash.data.SQLStatement; 
import flash.errors.SQLError; 
     
// ... create and open the SQLConnection instance named conn ... 
     
var createStmt:SQLStatement = new SQLStatement(); 
createStmt.sqlConnection = conn; 
     
var sql:String =  
    "CREATE TABLE IF NOT EXISTS employees (" +  
    "    empId INTEGER PRIMARY KEY AUTOINCREMENT, " +  
    "    firstName TEXT, " +  
    "    lastName TEXT, " +  
    "    salary NUMERIC CHECK (salary > 0)" +  
    ")"; 
createStmt.text = sql; 
     
try 
{ 
    createStmt.execute(); 
    trace("Table created"); 
} 
catch (error:SQLError) 
{ 
    trace("Error message:", error.message); 
    trace("Details:", error.details); 
} 
<?xml version="1.0" encoding="utf-8"?> 
<mx:WindowedApplication xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="init()"> 
    <mx:Script> 
        <![CDATA[ 
            import flash.data.SQLConnection; 
            import flash.data.SQLStatement; 
            import flash.errors.SQLError; 
             
            private function init():void 
            { 
                // ... create and open the SQLConnection instance named conn ... 
                 
                var createStmt:SQLStatement = new SQLStatement(); 
                createStmt.sqlConnection = conn; 
                 
                var sql:String =  
                    "CREATE TABLE IF NOT EXISTS employees (" +  
                    "    empId INTEGER PRIMARY KEY AUTOINCREMENT, " +  
                    "    firstName TEXT, " +  
                    "    lastName TEXT, " +  
                    "    salary NUMERIC CHECK (salary > 0)" +  
                    ")"; 
                createStmt.text = sql; 
                 
                try 
                { 
                    createStmt.execute(); 
                    trace("Table created"); 
                } 
                catch (error:SQLError) 
                { 
                    trace("Error message:", error.message); 
                    trace("Details:", error.details); 
                } 
            } 
        ]]> 
    </mx:Script> 
</mx:WindowedApplication>