`
zuroc
  • 浏览: 1289976 次
  • 性别: Icon_minigender_1
  • 来自: 江苏
社区版块
存档分类
最新评论

Firefox插件(XUL)开发 学习笔记 2.数据库的基本用法

阅读更多
书接上文,mDBConn.createStatement可以创建一个sql语句的模板,然后可以传入参数执行.

执行过后在通过reset方法重置它.

这样做的好处是:
"""
If you are doing a statement many times, using a precompiled statement will give you a noticable performance improvement because the SQL query doesn't need to be parsed each time.
"""

?1 在用 bindXXXXXParameter 时对应的位置的 0 , 而 ?2 对应的是 1 ... 以此类推 ... 哎,搞不清楚Moillza那群家伙是怎么想的...

还有一种更直观(也更繁琐的)绑定参数的方法 :myfirstparam  .用法如下:

var statement = mDBConn.createStatement("SELECT * FROM foo WHERE a = :myfirstparam AND b > :mysecondparam");

var firstidx = statement.getParameterIndex(":myfirstparam");
statement.bindUTF8StringParameter(firstidx, "hello");

var secondidx = statement.getParameterIndex(":mysecondparam");
statement.bindInt32Parameter(secondidx, 1234);

两种方法是可以混合使用的.


不过还是有局限,像下面这种情况还是自己拼装sql吧,不过小心sql注入:
"""
If you want to use a WHERE clause with an IN ( value-list ) expression, Bindings won't work

var ids = "3,21,72,89";
var sql = "DELETE FROM table WHERE id IN ( "+ ids +" )";
"""

有时候,我们不需要取得sql语句的返回值,那么像下面这样就可以了.

var statement = mDBConn.createStatement("INSERT INTO my_table VALUES (?1)");
statement.bindInt32Parameter(52);
statement.execute();

!!!牢牢记住,用完statement后要reset它,否则后果如下.
Un-reset write statements will keep a lock on the tables and will prevent other statements from accessing it. Un-reset read statements will prevent writes.

这种调用方式可以确保有异常时也可以reset,don't worry about unnecessary resets.

var statement = connection.createStatement(...);
try {
  // use the statement...
} finally {
  statement.reset();
}

当然如果你用.execute(),它会自动reset的.

如果你想获得刚刚插入数据的id,那么这么玩吧.

var sql = "INSERT INTO contacts_table (number_col, name_col) VALUES (?1, ?2)"
var statement = mDBConn.createStatement(sql);
    statement.bindUTF8StringParameter(0, number);
    statement.bindUTF8StringParameter(1, name);
    statement.execute();
var rowid = mDBConn.lastInsertRowID;//最后一条Insert语句产生的id

还有事务,说实话,我很讨厌sql,更讨厌事务,所以大家还是自己看文档吧,我复制一个演示用法.不过注意一点,由于sqlite是用的文件锁,加了事务会快上很多很多,大概的比例是1个小时=1分钟...这个我是有过惨痛经历的.

var ourTransaction = false;
if (!mDBConn.transactionInProgress) {
  ourTransaction = true;
  mDBConn.beginTransactionAs(mDBConn.TRANSACTION_DEFERRED);
}

// ... use the connection ...

if (ourTransaction)
  mDBConn.commitTransaction();


ok,到此为止,数据库大概操作基本够用了.
吾生也有涯,而知也无涯,以有涯随无涯,殆己!
所以不研究更深入了,现在浏览一下各个对象的接口.

1.
mozIStorageConnection
http://developer.mozilla.org/en/MozIStorageConnection

其中 createFunction 以及相关函数是用来创建sqlite函数的,参见
http://www.sqlite.org/c3ref/create_function.html
这里是sqlite的一些内置函数
http://www.sqlite.org/lang_corefunc.html
http://www.sqlite.org/lang_aggfunc.html

此外,应该是调用函数而不自己在sql创建事务

函数
void close();
mozIStorageStatement createStatement(in AUTF8String aSQLStatement);
void executeSimpleSQL(in AUTF8String aSQLStatement);
boolean tableExists(in AUTF8String aTableName);
boolean indexExists(in AUTF8String aIndexName);
void beginTransaction();
void beginTransactionAs(in PRInt32 transactionType);
void commitTransaction();
void rollbackTransaction();


void createTable(in string aTableName, in string aTableSchema);
aTableName
    The name of the table to create; table names may consist of the letters A-Z in either upper or lower case, the underscore, and the digits 0-9. The first character must be a letter.
aTableSchema
    The table's schema. This should be specified using the same syntax the CREATE TABLE statement uses. For example: "foo INTEGER, bar STRING".


void createFunction(in AUTF8String aFunctionName, in long aNumArguments, in mozIStorageFunction aFunction);
void createAggregateFunction(in AUTF8String aFunctionName, in long aNumArguments, in mozIStorageAggregateFunction aFunction);
void removeFunction(in AUTF8String aFunctionName);
mozIStorageProgressHandler setProgressHandler(in PRInt32 aGranularity, in mozIStorageProgressHandler aHandler);
mozIStorageProgressHandler removeProgressHandler();

属性
connectionReady boolean Indicates whether or not the connection is open or ready to use. This is false if the
connection failed to open or if it has been closed.

databaseFile nsIFile The current database file. NULL if the database connection refers to an in-memory database.

lastInsertRowID long long The row ID from the last SQL INSERT operation.

lastError long The last sqlite error code that occurred.

lastErrorString AUTF8String The English error string reported by the sqlite library for the last sqlite operation.

schemaVersion long The schema version of the database. This should not be used until the database is ready. The version will be reported as 0 if not set. since Gecko 1.9 M8

transactionInProgress boolean Returns true if there is a transaction in progress on the database; otherwise returns false.

常量
TRANSACTION_DEFERRED 0 Default. The database lock is acquired when needed.
TRANSACTION_IMMEDIATE 1 Get a read lock on the database immediately.
TRANSACTION_EXCLUSIVE 2 Get a write lock on the database immediately.

2.
mozIStorageStatement

函数

mozIStorageStatement clone();
AUTF8String getParameterName(in unsigned long aParamIndex);
unsigned long getParameterIndex(in AUTF8String aName);
AUTF8String getColumnName(in unsigned long aColumnIndex);
unsigned long getColumnIndex(in AUTF8String aName);
void reset();

void bindUTF8StringParameter(in unsigned long aParamIndex, in AUTF8String aValue);
void bindStringParameter(in unsigned long aParamIndex, in AString aValue);
void bindDoubleParameter(in unsigned long aParamIndex, in double aValue);
void bindInt32Parameter(in unsigned long aParamIndex, in long aValue);
void bindInt64Parameter(in unsigned long aParamIndex, in long long aValue);
void bindNullParameter(in unsigned long aParamIndex);
void bindBlobParameter(in unsigned long aParamIndex, [array,const,size_is(aValueSize)] in octet aValue, in unsigned long aValueSize);

void execute();

boolean executeStep();
The reset() method must be called on the statement after the last call of executeStep.


AString escapeStringForLIKE(in AString aValue, in wchar aEscapeChar);
An AString of an escaped version of aValue (%, _ and the escape char are escaped with the escape char).
For example, we will convert "foo/bar_baz%20cheese" into "foo//bar/_baz/%20cheese" (if the escape char is '/').


属性

parameterCount unsigned long Number of parameters.
columnCount unsigned long Number of columns returned.
state long The current state.

常量
Constant Value Description
MOZ_STORAGE_STATEMENT_INVALID 0 The SQL statement is Invalid.
MOZ_STORAGE_STATEMENT_READY 1 The SQL statement is ready to be executed.
MOZ_STORAGE_STATEMENT_EXECUTING 2 The SQL statement is executing at the moment.


3.
mozIStorageValueArray

函数
long getTypeOfIndex(in unsigned long aIndex);
long getInt32(in unsigned long aIndex);
long long getInt64(in unsigned long aIndex);
double getDouble(in unsigned long aIndex);
AUTF8String getUTF8String(in unsigned long aIndex);
AString getString(in unsigned long aIndex);
void getBlob(in unsigned long aIndex, out unsigned long aDataSize, [array,size_is(aDataSize)] out octet aData);
boolean getIsNull(in unsigned long aIndex);

属性
numEntries unsigned long The number of entries in the array (each corresponding to a column in the database row).

常量
Constant Value Description
VALUE_TYPE_NULL 0 Null data type.
VALUE_TYPE_INTEGER 1 INTEGER data type.
VALUE_TYPE_FLOAT 2 FLOAT data type.
VALUE_TYPE_TEXT 3 TEXT data type.
VALUE_TYPE_BLOB 4 BLOB data type.


4.
mozIStorageService
函数
nsIFile backupDatabaseFile(in nsIFile aDBFile, in AString aBackupFileName, [optional] in nsIFile aBackupParentDirectory);
mozIStorageConnection openDatabase(in nsIFile aDatabaseFile);
mozIStorageConnection openSpecialDatabase(in string aStorageKey);
mozIStorageConnection openUnsharedDatabase(in nsIFile aDatabaseFile);
分享到:
评论
1 楼 sunfengcheng 2008-08-25  
很基础!但倒是很有必要!收了!

相关推荐

Global site tag (gtag.js) - Google Analytics