Working with the SQLite-Database - Cursors

本文介绍如何在Android应用中使用内置的SQLite数据库服务器来创建数据库和表格、插入数据集及进行查询。通过具体步骤演示了创建数据库、打开数据库、创建表格、插入数据、查询数据以及关闭数据库的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

What you learn:You will learn how tocreatedatabases andtables,insertandquerydatasets in the Android-built-inSQLite-DataBase-Server.

Difficulty:1 of 5Smile

IdeaQuestions/Problems:Simply post below...

What it will look like:



Description:
We'll need to to the following things:
  1. Create a DataBase(generally this is done just once)
  2. Open the DataBase
  3. Create a Table(generally this is done just once)
  4. Insert some Datasets
  5. Query for some Datasets
  6. Close the Database

0.)So lets work it out:
We first do some setup. Declaring the DataBases/Tables we are using as final should always be preferred before typing the name to every single statement. (Changes are a lot easier !).
Java:
publicclassDataBaseWorkextendsListActivity{

privatefinalStringMY_DATABASE_NAME ="myCoolUserDB";
privatefinalStringMY_DATABASE_TABLE ="t_Users";

/** Called when the activity is first created. */
@Override
publicvoidonCreate(Bundle icicle){
super.onCreate(icicle);
/* Will hold the 'Output' we want to display at the end. */
ArrayListresults =newArrayList();


1.)So lets create the DataBase:
Java:
SQLiteDatabase myDB =null;
try{
/* Create the Database (no Errors if it already exists) */
this.createDatabase(MY_DATABASE_NAME,1, MODE_PRIVATE,null);


2.)Having created the DataBase we want to open it:
Java:
/* Open the DB and remember it */
myDB =this.openDatabase(MY_DATABASE_NAME,null);


3.)Now we create a simple Table with just four columns:
Java:
/* Create a Table in the Database. */
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ MY_DATABASE_TABLE
+" (LastName VARCHAR, FirstName VARCHAR,"
+" Country VARCHAR, Age INT(3));");

4.)Put two DataSets to the recently created Table:
Java:
/* Add two DataSets to the Table. */
myDB.execSQL("INSERT INTO "
+ MY_DATABASE_TABLE
+" (LastName, FirstName, Country, Age)"
+" VALUES ('Gramlich', 'Nicolas', 'Germany', 20);");
myDB.execSQL("INSERT INTO "
+ MY_DATABASE_TABLE
+" (LastName, FirstName, Country, Age)"
+" VALUES ('Doe', 'John', 'US', 34);");

5.)Having written some DataSets to the Table, we would want to receive them back somewhen. Thr result of a query is a Cursor that can move over all the results returned by the query. We apply Projection (Just the Specified Columns) and Selection (WHERE ...) to it and a LIMIT. Just as we would do in any other SQL-"Dialect":
Java:
/* Query for some results with Selection and Projection. */
Cursorc = myDB.query("SELECT FirstName,Age"+
" FROM "+ MY_DATABASE_TABLE
+" WHERE Age > 10 LIMIT 7;",
null);

6.)Now having queried, we retrieve the ColumIndexes of two Columns calling thegetColumnIndex(String);-method of the Cursor:
Java:
/* Get the indices of the Columns we will need */
intfirstNameColumn = c.getColumnIndex("FirstName");
intageColumn = c.getColumnIndex("Age");

/* Check if our result was valid. */
if(c !=null){
/* Check if at least one Result was returned. */
if(c.first()){
inti =0;
/* Loop through all Results */
do{
i++;
/* Retrieve the values of the Entry
* the Cursor is pointing to. */

StringfirstName = c.getString(firstNameColumn);
intage = c.getInt(ageColumn);
/* We can also receive the Name
* of a Column by its Index.
* Makes no sense, as we already
* know the Name, but just to shwo we canWink*/

StringageColumName = c.getColumnName(ageColumn);

/* Add current Entry to results. */
results.add(""+ i +": "+ firstName
+" ("+ ageColumName +": "+ age +")");
}while(c.next());
}
}

7.)Finally close the DataBase (if it has been opened):
Java:
}catch(FileNotFoundExceptione){
}finally{
if(myDB !=null)
myDB.close();
}

8.)In the end, display our Entries:
Java:
this.setListAdapter(newArrayAdapter(this,
android.R.layout.simple_list_item_1_small, results));
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值