導航:首頁 > 操作系統 > androidsqlite資料庫操作

androidsqlite資料庫操作

發布時間:2022-08-20 02:46:49

1. android開發中的SQLite資料庫的增刪改查功能怎麼實現

SQLite是一個輕量級的嵌入式資料庫引擎,它支持SQL語言,並且佔用很少的內存就可以有很好的性能。它與其他資料庫的最大的不同就是對數據類型的支持,創建一個表時,可以在CREATE

TABLE語句中指定某列的數據類型,但是可以把任何數據類型放入任何列中。當某個值插入資料庫時,SQLite將檢查它的數據類型。如果該類型和關聯的列不匹配,那麼SQLite會嘗試將該值轉換成該列的數據類型,如果不能轉換,那麼該值將作為其本身具有的數據類型存儲。對於Android平台來說,系統內置了豐富的API(SQLiteDatabase、SQLiteOpenHelper,Cursor等)來供我們操作SQLite。那麼接下來我將會結合我的代碼來講述我對Android資料庫的理解。

2. android 怎麼查看sqlite資料庫

在Android中查看和管理sqlite資料庫

在Android中可以使用Eclipse插件DDMS來查看,也可以使用Android工具包中的adb工具來查看。android
項目中的sqlite資料庫位於/data/data/項目包/databases中。
使用DDMS導出sqlite資料庫。

1、首先打開android項目的調試模式,然後找到顯示DDMS:

選擇DDMS

2、切換到DDMS,顯示File Explorer窗口,找到/data/data/

然後找到程序包的文件夾,打開databases,就能看到sqlite資料庫文件了。選擇將其導出。

這樣就把sqlite資料庫文件以文件的方式導出來了,然後使用sqlite界面管理工具如
sqlite administrator、sqlite man或者firefox插件sqlite manager等打開就可以了。

使用adb工具訪問sqlite資料庫

Android Debug Bridge(ADB)是Android的一個通用調試工具,它可以更新設備或模擬器中的代碼,
可以管理預定埠,可以在設備上運行shell命令,我們知道android是基於linux內核,它的內部
文件結構也是採用linux文件組織方式,因此訪問它的文件結構需要使用shell。這次我們就會用shell
來訪問android應用中的sqlite資料庫文件。

1、運行cmd,切換到android-sdk目錄,運行adb.exe,加上參數shell,出現#號就代表進入了shell
命令模式,注意adb要在Android模擬器運行時才能進入shell:

2、shell命令記住兩個基本命令ls和cd,類似windows命令提示行中的dir和cd,代表列出當前目錄下
文件列表和進入到指定目錄。了解這兩個命令之後,就可以找到data/data/項目包名/databases:

找到資料庫文件:

接下來就是使用sqlite管理工具來進行操作了。鍵入sqlite3 資料庫名就進入了sqlite管理模式了。

在android的sdk中自帶了sqlite3.exe,這是sqlite的官方管理工具,它是一個命令行工具。為了使用
方便,將其路徑注冊到系統環境變數path中,即將;%Android_Home%加在Path中,這樣只樣運行sqlite3
,就能直接打開sqlite管理工具了。

sqlite管理資料庫篇

sqlite命令行工具默認是以;結束語句的。所以如果只是一行語句,要在末尾加;,或者在下一行中鍵入
;,這樣sqlite命令才會被執行。

sqlite常用命令:

.tables--查看資料庫的表列表

.exit--退出sqlite命令行

其他命令可隨時.help查看幫助。sql命令可直接在此命令行上執行即可

3. android sqlite資料庫怎麼使用

其主要思路是:

1. 把資料庫分解成幾個asset文件。

2. 當需要打開資料庫時,如果資料庫不存在,就把那幾個asset文件重新合並成一個資料庫文件。

3. 如果資料庫的版本改變了,就在onUpgrade()方法中把資料庫文件刪除掉。

下面是代碼:

//資料庫的預設路徑

private static finalString DB_PATH = "/data/data/com.mypackage.myapp/databases/";

private static finalString DB_NAME = "mydb.db";

private static finalint DB_VERSION = 2;

private static finalString DB_SPLIT_NAME = "mydb.db.00";

private static finalint DB_SPLIT_COUNT = 3;

private SQLiteDatabasem_database;

private final Contextm_context;

/**

* Constructor

*保存傳進來的context參數以用來訪問應用的asset和資源文件。

* @param context

*/

public MyDB(Contextcontext) {

super(context, DB_NAME, null, DB_VERSION);

this.m_context = context;

}

public static MyDBopenDatabaseReadOnly(Context context) {

MyDB db = new MyDB(context);

try {

db.createDataBase();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

db.openDataBase(SQLiteDatabase.OPEN_READONLY);

return db;

}

public static MyDBopenDatabaseReadWrite(Context context) {

MyDB db = new MyDB(context);

try {

db.createDataBase();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

db.openDataBase(SQLiteDatabase.OPEN_READWRITE);

return db;

}

/**

*創建一個空資料庫,用來存儲你已有的資料庫。

*/

public voidcreateDataBase() throws IOException{

boolean dbExist =checkDataBase();

if (dbExist) {

/*

**如果你的資料庫的版本改變了,調用這個方法確保在onUpgrade()被調用時

**傳進去的是可寫的資料庫。

*/

SQLiteDatabase db =this.getWritableDatabase();

if (db != null) {

db.close();

}

}

dbExist = checkDataBase();

if (!dbExist) {

try {

/*

** 調用這個方法以確保在預設路徑內產生一個空資料庫,以便在其基礎上復制我們已有的資料庫。

*/

SQLiteDatabase db =this.getReadableDatabase();

if (db != null) {

db.close();

}

DataBase();

}

catch (IOException e) {

Log.e("DB", e.getMessage());

throw new Error("Error ingdatabase");

}

}

}

/**

* 檢查資料庫是否已存在,以避免重復復制。

* @return true if it exists, false if itdoesn't

*/

private static booleancheckDataBase(){

SQLiteDatabase checkDB = null;

try {

String path = DB_PATH + DB_NAME;

checkDB =SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);

}

catch (SQLiteException e){

//database does't exist yet.

}

if (checkDB != null) {

checkDB.close();

}

return checkDB != null ? true : false;

}

/**

* 把存在asset文件中的資料庫復制的剛創建的空資料庫中。

* */

private voidDataBase() throws IOException {

// 剛創建的空資料庫的路徑

String outFileName = DB_PATH + DB_NAME;

// 打開空資料庫

OutputStream output = new FileOutputStream(outFileName);

byte[] buffer = new byte[1024*8];

AssetManager assetMgr =m_context.getAssets();

for (int i = 1; i <= DB_SPLIT_COUNT; i++){

// 打開分解的asset文件

String fn = DB_SPLIT_NAME +String.valueOf(i);

InputStream input = assetMgr.open(fn);

//Log.i("DB", "opened" + fn);

int length;

while ((length = input.read(buffer)) >0) {

//Log.i("DB", "read" + String.valueOf(length));

output.write(buffer, 0, length);

//Log.i("DB", "write" + String.valueOf(length));

}

input.close();

}

//Close the streams

output.flush();

output.close();

}

/**

* 打開資料庫。

* */

private voidopenDataBase(int flags) throws SQLException{

//Open the database

String myPath = DB_PATH + DB_NAME;

m_database =SQLiteDatabase.openDatabase(myPath, null, flags);

}

/**

* 關閉資料庫。

* */

@Override

public synchronizedvoid close() {

if (m_database != null)

m_database.close();

super.close();

}

}

@Override

public voidonCreate(SQLiteDatabase db) {

// 不需做任何事

}

/**

* 在資料庫版本提高時,刪除原有資料庫。

* */

@Override

public voidonUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

if (newVersion > oldVersion) {

m_context.deleteDatabase(DB_NAME);

}

}

4. 安卓怎麼讀取sqlite資料庫

安裝SQLite Expert Professional 可以在網上下載,我下載的是試用版,沒有找注冊碼,但是試用不影響使用,反正用幾次查看到資料庫操作沒有錯誤就不用這個工具了。當然也可以使用Eclipse插件DDMS來查看,也可以使用Android工具包中的adb工具來查看。android項目中的sqlite資料庫位於/data/data/項目包/databases中。先介紹使用DDMS導出sqlite資料庫的操作和使用adb工具訪問sqlite資料庫。
首先打開android項目的調試模式,然後找到顯示DDMS

切換到DDMS,顯示File Explorer窗口,找到/data/data/ 如下圖1 ,
然後找到程序包的文件夾,打開databases,就能看到sqlite資料庫文件了。選擇將其導出。如下圖2.
這樣就把sqlite資料庫文件以文件的方式導出來了,然後使用sqlite界面管理工具如SQLite Expert Professional可以打開該資料庫了。其他 sqlite界面管理工具如sqlite administrator、sqlite man或者firefox插件sqlite manager也可以打開該資料庫。

使用adb工具訪問sqlite資料庫
Android Debug Bridge(ADB)是Android的一個通用調試工具,它可以更新設備或模擬器中的代碼,可以管理預定埠,可以在設備上運行shell命令,我們 知道android是基於Linux內核,它的內部文件結構也是採用linux文件組織方式,因此訪問它的文件結構需要使用shell。這次我們就會用 shell來訪問android應用中的sqlite資料庫文件。
1、運行cmd,切換到android-sdk目錄,運行adb.exe,加上參數shell,出現#號就代表進入了shell命令模式,注意adb要在Android模擬器運行時才能進入shell:如下圖

進入資料庫所在目錄:
shell命令記住兩個基本命令ls和cd,類似windows命令提示行中的dir和cd,代表列出當前目錄下文件列表和進入到指定目錄。了解這兩個命令之後,就可以找到data/data/項目包名/databases 如下圖1, 找到資料庫文件如下圖2。

使用sqlite管理工具來進行資料庫操作
鍵入sqlite3 資料庫名就進入了sqlite管理模式了。
如下圖

設置sqlite環境變數:
在android的sdk中自帶了sqlite3.exe,這是sqlite的官方管理工具,它是一個命令行工具。為了使用方便,將其路徑注冊到系 統環境變數path中,即將;%Android_Home%加在Path中,這樣只樣運行sqlite3,就能直接打開sqlite管理工具了。
如下圖:

8
使用sqlite管理資料庫:
sqlite命令行工具默認是以;結束語句的。所以如果只是一行語句,要在末尾加;,或者在下一行中鍵入;,這樣sqlite命令才會被執行。
sqlite常用命令:
.tables--查看資料庫的表列表
.exit--退出sqlite命令行
其他命令可隨時.help查看幫助。sql命令可直接在此命令行上執行即可:

5. 安卓怎麼使用sqlite資料庫

使用sql語句命令創建SQLite資料庫需要專業的知識,例如sql語句,等等 建議你使用SQLitem客戶端來操作,可以創建表,加欄位改欄位,設置索引觸發器等等 最後還可以生成sql腳本,做開發的不可能用這個命令行來操作的 SQLiteDev已經上傳附件 SQLiteDve 自帶語法高亮,代碼提示的功能性,非常方便 SqliteDev385.zip大小:8.33M所需財富值:5 已經過網路安全檢測,放心下載 點擊下載下載量:0

6. 關於android中使用SQLite資料庫的查詢基本操作.貼上代碼.

sqlite\.classpath
......\.project
......\.settings\org.eclipse.jdt.core.prefs
......\AndroidManifest.xml
......\bin\AndroidManifest.xml
......\...\classes\mars\sqlite3\BuildConfig.class
......\...\.......\....\.......\db\DatabaseHelper.class
......\...\.......\....\.......\R$attr.class
......\...\.......\....\.......\R$drawable.class
......\...\.......\....\.......\R$id.class
......\...\.......\....\.......\R$layout.class
......\...\.......\....\.......\R$string.class
......\...\.......\....\.......\R.class
......\...\.......\....\.......\SQLiteActivity$CreateListener.class
......\...\.......\....\.......\SQLiteActivity$InsertListener.class
......\...\.......\....\.......\SQLiteActivity$QueryListener.class
......\...\.......\....\.......\SQLiteActivity$UpdateListener.class
......\...\.......\....\.......\SQLiteActivity$UpdateRecordListener.class
......\...\.......\....\.......\SQLiteActivity.class
......\...\classes.dex
......\...\dexedLibs\annotations-.jar
......\...\jarlist.cache
......\...\res\drawable-hdpi\icon.png
......\...\...\.........ldpi\icon.png
......\...\...\.........mdpi\icon.png
......\...\resources.ap_
......\...\sqlite.apk
......\gen\mars\sqlite3\BuildConfig.java
......\...\....\.......\R.java
......\project.properties
......\res\drawable-hdpi\icon.png
......\...\.........ldpi\icon.png
......\...\.........mdpi\icon.png
......\...\layout\main.xml
......\...\values\strings.xml
......\src\mars\sqlite3\db\DatabaseHelper.java
......\...\....\.......\SQLiteActivity.java
......\bin\classes\mars\sqlite3\db
......\...\.......\....\sqlite3
......\src\mars\sqlite3\db
......\bin\classes\mars
......\...\res\drawable-hdpi
......\...\...\drawable-ldpi
......\...\...\drawable-mdpi
......\gen\mars\sqlite3
......\src\mars\sqlite3
......\bin\classes
......\...\dexedLibs
......\...\res
......\gen\mars
......\res\drawable-hdpi
......\...\drawable-ldpi
......\...\drawable-mdpi
......\...\drawable-xhdpi
......\...\layout
......\...\values
......\src\mars
......\.settings
......\assets
......\bin
......\gen
......\res
......\src
sqlite

7. 如何使用SQLite,Android上SQLite的最佳實踐

SQLite3是目前最新的SQLite版本。可以從網站上下載SQLite3的源代碼(本書使用的版本是sqlite-3.6.12.tar.gz)。
壓縮後進入sqlite-3.6.12的根目錄,首先命令「./configure」生成Makefile文件,接著運行命令「make」對源代碼進行編譯,最後運行命令「make install」安裝SQLite3。安裝完畢後,可以運行命令sqlite3查看SQLite3是否能正常運行,如下所示:
[root@localhost ~]# sqlite3
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite>
可以看到,SQLite3啟動後會停留在提示符sqlite>處,等待用戶輸入SQL語句。
在使用SQLite3前需要先了解下SQLite3支持的數據類型。SQLite3支持的基本數據類型主要有以下幾類:
NULL
NUMERIC
INTEGER
REAL
TEXT
SQLite3會自動把其他數據類型轉換成以上5類基本數據類型,轉換規則如下所示:
char、clob、test、varchar—> TEXT
integer—>INTEGER
real、double、float—> REAL
blob—>NULL
其餘數據類型都轉變成NUMERIC
下面通過一個實例來演示SQLite3的使用方法。
新建一個資料庫
新建資料庫test.db(使用.db後綴是為了標識資料庫文件)。在test.db中新建一個表test_table,該表具有name,、sex、age三列。SQLite3的具體操作如下所示:
[root@localhost home]# sqlite3 test.db
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> create table test_table(name, sex, age);
如果資料庫test.db已經存在,則命令「sqlite3 test.db」會在當前目錄下打開test.db。如果資料庫test.db不存在,則命令「sqlite3 test.db」會在當前目錄下新建資料庫test.db。為了提高效率,SQLite3並不會馬上創建test.db,而是等到第一個表創建完成後才會在物理上創建資料庫。
由於SQLite3能根據插入數據的實際類型動態改變列的類型,所以在create語句中並不要求給出列的類型。
創建索引
為了加快表的查詢速度,往往在主鍵上添加索引。如下所示的是在name列上添加索引的過程。
sqlite> create index test_index on test_table(name);
操作數據
如下所示的是在test_table中進行數據的插入、更新、刪除操作:
sqlite> insert into test_table values ('xiaoming', 'male', 20);
sqlite> insert into test_table values ('xiaohong', 'female', 18);
sqlite> select * from test_table;
xiaoming|male|20
xiaohong|female|18
sqlite> update test_table set age=19 where name = 'xiaohong';
sqlite> select * from test_table;
xiaoming|male|20
xiaohong|female|19
sqlite> delete from test_table where name = 'xiaoming';
sqlite> select * from test_table;
xiaohong|female|19
批量操作資料庫
如下所示的是在test_table中連續插入兩條記錄:
sqlite> begin;
sqlite> insert into test_table values ('xiaoxue', 'female', 18);
sqlite> insert into test_table values ('xiaoliu', 'male', 20);
sqlite> commit;
sqlite> select * from test_table;
xiaohong|female|19
xiaoxue|male|18
xiaoliu|male|20
運行命令commit後,才會把插入的數據寫入資料庫中。
資料庫的導入導出
如下所示的是把test.db導出到sql文件中:
[root@localhost home]# sqlite3 test.db ".mp" > test.sql;
test.sql文件的內容如下所示:
BEGIN TRANSACTION;
CREATE TABLE test_table(name, sex, age);
INSERT INTO "test_table" VALUES('xiaohong','female',19);
CREATE INDEX test_index on test_table(name);
COMMIT;
如下所示的是導入test.sql文件(導入前刪除原有的test.db):
[root@localhost home]# sqlite3 test.db < test.sql;
通過對test.sql文件的導入導出,可以實現資料庫文件的備份。
11.2.2 SQLite3的C介面
以上介紹的是SQLite3資料庫的命令操作方式。在實際使用中,一般都是應用程序需要對資料庫進行訪問。為此,SQLite3提供了各種編程語言的使用介面(本書介紹C語言介面)。SQLite3具有幾十個C介面,下面介紹一些常用的C介面。
sqlite_open
作用:打開SQLite3資料庫
原型:int sqlite3_open(const char *dbname, sqlite3 **db)
參數:
dbname:資料庫的名稱;
db:資料庫的句柄;
sqlite_colse
作用:關閉SQLite3資料庫
原型:int sqlite_close(sqlite3 *db)
例如:
test.c:
#include <stdio.h>
#include <sqlite3.h>

static sqlite3 *db=NULL;

int main()
{
int rc;
rc= sqlite3_open("test.db", &db);

if(rc)
{
printf("can't open database!\n");
}
else
{
printf("open database success!\n");
}

sqlite3_close(db);
return 0;
}
運行命令「gcc –o test test.c –lsqlite3」進行編譯,運行test的結果如下所示:
[root@localhost home]# open database success!
sqlite_exec
作用:執行SQL語句
原型:int sqlite3_exec(sqlite3 *db, const char *sql, int (*callback)(void*,int,char**,char**), void *, char **errmsg)
參數:
db:資料庫;
sql:SQL語句;
callback:回滾;
errmsg:錯誤信息
例如:
test.c:
#include <stdio.h>
#include <sqlite3.h>

static sqlite3 *db=NULL;
static char *errmsg=NULL;

int main()
{
int rc;

rc = sqlite3_open("test.db", &db);
rc = sqlite3_exec(db,"insert into test_table values('bao', 'male', 24)", 0, 0, &errmsg);

if(rc)
{
printf("exec fail!\n");
}
else
{
printf("exec success!\n");
}

sqlite3_close(db);
return 0;
}
編譯完成後,運行test的結果如下所示:
[root@localhost home]# ./test
exec success!
[root@localhost home]# sqlite3 test.db
SQLite version 3.6.11
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> select * from test_table;
bao|male|24
sqlite3_get_table
作用:執行SQL查詢
原型:int sqlite3_get_table(sqlite3 *db, const char *zSql, char ***pazResult, int *pnRow, int *pnColumn, char **pzErrmsg)
參數:
db:資料庫;
zSql:SQL語句;
pazResult:查詢結果集;
pnRow:結果集的行數;
pnColumn:結果集的列數;
errmsg:錯誤信息;
sqlite3_free_table
作用:注銷結果集
原型:void sqlite3_free_table(char **result)
參數:
result:結果集;
例如:
test.c:
#include <stdio.h>
#include <sqlite3.h>

static sqlite3 *db=NULL;
static char **Result=NULL;
static char *errmsg=NULL;

int main()
{
int rc, i, j;
int nrow;
int ncolumn;

rc= sqlite3_open("test.db", &db);
rc= sqlite3_get_table(db, "select * from test_table", &Result, &nrow, &ncolumn,
&errmsg);

if(rc)
{
printf("query fail!\n");
}
else
{
printf("query success!\n");
for(i = 1; i <= nrow; i++)
{
for(j = 0; j < ncolumn; j++)
{
printf("%s | ", Result[i * ncolumn + j]);
}
printf("\n");
}
}

sqlite3_free_table(Result);
sqlite3_close(db);
return 0;
}
編譯完成後,運行test的結果如下所示:
[root@localhost home]# ./test
query success!
xiaohong | female | 19 |
xiaoxue | female | 18 |
xiaoliu | male | 20 |
bao | male | 24 |
sqlite3_prepare
作用:把SQL語句編譯成位元組碼,由後面的執行函數去執行
原型:int sqlite3_prepare(sqlite3 *db, const char *zSql, int nByte, sqlite3_stmt **stmt, const char **pTail)
參數:
db:資料庫;
zSql:SQL語句;
nByte:SQL語句的最大位元組數;
stmt:Statement句柄;
pTail:SQL語句無用部分的指針;
sqlite3_step
作用:步步執行SQL語句位元組碼
原型:int sqlite3_step (sqlite3_stmt *)
例如:
test.c:
#include <stdio.h>
#include <sqlite3.h>

static sqlite3 *db=NULL;
static sqlite3_stmt *stmt=NULL;

int main()
{
int rc, i, j;
int ncolumn;

rc= sqlite3_open("test.db", &db);
rc=sqlite3_prepare(db,"select * from test_table",-1,&stmt,0);

if(rc)
{
printf("query fail!\n");
}
else
{
printf("query success!\n");
rc=sqlite3_step(stmt);
ncolumn=sqlite3_column_count(stmt);
while(rc==SQLITE_ROW)
{
for(i=0; i<2; i++)
{
printf("%s | ", sqlite3_column_text(stmt,i));
}
printf("\n");
rc=sqlite3_step(stmt);
}
}

sqlite3_finalize(stmt);
sqlite3_close(db);
return 0;
}
編譯完成後,運行test的結果如下所示:
[root@localhost home]# ./test
query success!
xiaohong | female | 19 |
xiaoxue | female | 18 |
xiaoliu | male | 20 |
bao | male | 24 |
在程序中訪問SQLite3資料庫時,要注意C API的介面定義和數據類型是否正確,否則會得到錯誤的訪問結果。

閱讀全文

與androidsqlite資料庫操作相關的資料

熱點內容
androidbringup 瀏覽:977
演算法設計與分析英文版 瀏覽:910
java程序員加班嗎 瀏覽:141
編譯檢查的是什麼錯誤 瀏覽:405
加密兔f碼生成器免費 瀏覽:292
思科路由器命令明文加密 瀏覽:171
方舟生存進化伺服器如何改名字 瀏覽:892
央行數字貨幣app怎麼注冊 瀏覽:431
51單片機顯示時間 瀏覽:770
我的世界網易版怎麼壓縮地圖 瀏覽:682
qq小程序雲伺服器和 瀏覽:740
方舟伺服器怎麼玩才好玩 瀏覽:557
單片機的部件 瀏覽:621
編譯原理遍的過程 瀏覽:268
python讀取json字元串 瀏覽:72
ubuntu1404安裝php 瀏覽:636
lua能編譯嗎 瀏覽:118
思仙怎麼看伺服器 瀏覽:660
php微信圖片防盜鏈 瀏覽:800
安卓1怎麼讀音 瀏覽:298