要向数据库中的表添加数据,请创建并执行其文本为 SQL
INSERT
语句的
SQLStatement
实例。
以下示例使用 SQLStatement 实例向已存在的 employees 表添加数据行。此示例演示如何使用异步执行模式插入数据。请注意,此列表假定存在一个名为
conn
的
SQLConnection
实例,并且该实例已经实例化并连接到数据库。它还假定已创建“employees”表。
// Include AIRAliases.js to use air.* shortcuts
// ... create and open the SQLConnection instance named conn ...
// create the SQL statement
var insertStmt = new air.SQLStatement();
insertStmt.sqlConnection = conn;
// define the SQL text
var sql =
"INSERT INTO employees (firstName, lastName, salary) " +
"VALUES ('Bob', 'Smith', 8000)";
insertStmt.text = sql;
// register listeners for the result and failure (status) events
insertStmt.addEventListener(air.SQLEvent.RESULT, insertResult);
insertStmt.addEventListener(air.SQLErrorEvent.ERROR, insertError);
// execute the statement
insertStmt.execute();
function insertResult(event)
{
air.trace("INSERT statement succeeded");
}
function insertError(event)
{
air.trace("Error message:", event.error.message);
air.trace("Details:", event.error.details);
}
以下示例使用同步执行模式向已存在的 employees 表添加数据行。请注意,此列表假定存在一个名为
conn
的
SQLConnection
实例,并且该实例已经实例化并连接到数据库。它还假定已创建“employees”表。
// Include AIRAliases.js to use air.* shortcuts
// ... create and open the SQLConnection instance named conn ...
// create the SQL statement
var insertStmt = new air.SQLStatement();
insertStmt.sqlConnection = conn;
// define the SQL text
var sql =
"INSERT INTO employees (firstName, lastName, salary) " +
"VALUES ('Bob', 'Smith', 8000)";
insertStmt.text = sql;
try
{
// execute the statement
insertStmt.execute();
air.trace("INSERT statement succeeded");
}
catch (error)
{
air.trace("Error message:", error.message);
air.trace("Details:", error.details);
}