Android——使用SQLite数据库访问

SQLite

 

         SQLite,是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源世界著名的数据库管理系统来讲,它的处理速度比他们都快。SQLite第一个Alpha版本诞生于2000年5月。至今已经有12个年头,SQLite也迎来了一个版本 SQLite 3已经发布。

 

一、界面


 

 

二、程序包结构


 

 

三、layout中包含2给配置文件,main.xml(里面包含一个ListView控件)和person.xml(与ListView对应的TextView)

main.xml

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <LinearLayout  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:orientation="horizontal" >  
  11.   
  12.         <TextView  
  13.             android:layout_width="wrap_content"  
  14.             android:layout_height="wrap_content"  
  15.             android:layout_weight="1"  
  16.             android:text="编号"  
  17.             android:textSize="18sp" />  
  18.   
  19.         <TextView  
  20.             android:layout_width="wrap_content"  
  21.             android:layout_height="wrap_content"  
  22.             android:layout_weight="1"  
  23.             android:text="姓名"  
  24.             android:textSize="18sp" />  
  25.   
  26.         <TextView  
  27.             android:layout_width="wrap_content"  
  28.             android:layout_height="wrap_content"  
  29.             android:layout_weight="1"  
  30.             android:text="年龄"  
  31.             android:textSize="18sp" />  
  32.     </LinearLayout>  
  33.   
  34.     <ListView  
  35.         xmlns:android="http://schemas.android.com/apk/res/android"  
  36.         android:id="@+id/listView"  
  37.         android:layout_width="fill_parent"  
  38.         android:layout_height="wrap_content" />  
  39.   
  40. </LinearLayout>  

 

person.xml

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:id="@+id/id"  
  9.         android:layout_width="120px"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_alignParentLeft="true"  
  12.         android:layout_alignParentTop="true"  
  13.         android:layout_margin="3dip"  
  14.         android:text="TextView"  
  15.         android:textAppearance="?android:attr/textAppearanceLarge" />  
  16.   
  17.     <TextView  
  18.         android:id="@+id/name"  
  19.         android:layout_width="180px"  
  20.         android:layout_height="wrap_content"  
  21.         android:layout_alignParentTop="true"  
  22.         android:layout_margin="3dip"  
  23.         android:layout_toRightOf="@+id/id"  
  24.         android:text="TextView"  
  25.         android:textAppearance="?android:attr/textAppearanceLarge" />  
  26.   
  27.     <TextView  
  28.         android:id="@+id/age"  
  29.         android:layout_width="50px"  
  30.         android:layout_height="wrap_content"  
  31.         android:layout_alignParentTop="true"  
  32.         android:layout_margin="3dip"  
  33.         android:layout_toRightOf="@+id/name"  
  34.         android:text="TextView"  
  35.         android:textAppearance="?android:attr/textAppearanceLarge" />  
  36.   
  37. </RelativeLayout>  

 

 

四、AndroidManifest.xml,配置了Android单元测试

Xml代码   收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="org.e276.db"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.       
  7.     <uses-sdk android:minSdkVersion="10" />  
  8.   
  9.     <application  
  10.         android:icon="@drawable/ic_launcher"  
  11.         android:label="@string/app_name" >  
  12.           
  13.          <!-- Android配置单元测试 -->  
  14.         <uses-library android:name="android.test.runner" />  
  15.           
  16.         <activity  
  17.             android:name=".MainActivity"  
  18.             android:label="@string/app_name" >  
  19.             <intent-filter>  
  20.                 <action android:name="android.intent.action.MAIN" />  
  21.   
  22.                 <category android:name="android.intent.category.LAUNCHER" />  
  23.             </intent-filter>  
  24.         </activity>  
  25.     </application>  
  26.   
  27.     <!-- Android配置单元测试 -->  
  28.     <instrumentation   
  29.         android:name="android.test.InstrumentationTestRunner"   
  30.         android:targetPackage="org.e276.db" />  
  31.       
  32. </manifest>  

 

 

五、entity

Java代码   收藏代码
  1. package org.e276.entity;  
  2.   
  3. /** 
  4.  * 实体类 
  5.  *  
  6.  * @author miao 
  7.  *  
  8.  */  
  9. public class Person {  
  10.   
  11.     private Integer id;  
  12.     private String name;  
  13.     private Integer age;  
  14.   
  15.     public Person() {  
  16.         super();  
  17.     }  
  18.   
  19.     public Person(Integer id, String name, Integer age) {  
  20.         super();  
  21.         this.id = id;  
  22.         this.name = name;  
  23.         this.age = age;  
  24.     }  
  25.   
  26.     public Integer getId() {  
  27.         return id;  
  28.     }  
  29.   
  30.     public void setId(Integer id) {  
  31.         this.id = id;  
  32.     }  
  33.   
  34.     public String getName() {  
  35.         return name;  
  36.     }  
  37.   
  38.     public void setName(String name) {  
  39.         this.name = name;  
  40.     }  
  41.   
  42.     public Integer getAge() {  
  43.         return age;  
  44.     }  
  45.   
  46.     public void setAge(Integer age) {  
  47.         this.age = age;  
  48.     }  
  49.   
  50.     @Override  
  51.     public String toString() {  
  52.         return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";  
  53.     }  
  54.   
  55. }  

 

 

六、dao,带一dao辅助类

DBHelper.java

Java代码   收藏代码
  1. package org.e276.dao;  
  2.   
  3. import android.content.Context;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5. import android.database.sqlite.SQLiteOpenHelper;  
  6.   
  7. /** 
  8.  * 数据库辅助类 
  9.  *  
  10.  * @author miao 
  11.  *  
  12.  */  
  13. public class DBHelper extends SQLiteOpenHelper {  
  14.   
  15.     /* 
  16.      * @param context 上下文 
  17.      *  
  18.      * @param name 数据库名字 
  19.      *  
  20.      * @param factory 游标工厂对象,没指定就设置为null 
  21.      *  
  22.      * @param version 版本号 
  23.      */  
  24.     // public DBHelper(Context context, String name, CursorFactory factory,  
  25.     // int version) {  
  26.     // super(context, name, factory, version);  
  27.     // }  
  28.   
  29.     private static final String DB_NAME = "ali.db";  
  30.     private static final int VERSION = 1;  
  31.   
  32.     public DBHelper(Context context) {  
  33.         super(context, DB_NAME, null, VERSION);  
  34.     }  
  35.   
  36.     /** 
  37.      * 第一次运行的时候创建 
  38.      */  
  39.     @Override  
  40.     public void onCreate(SQLiteDatabase db) {  
  41.         db.execSQL("CREATE TABLE IF NOT EXISTS person (personid integer primary key autoincrement, name text, age INTEGER)");  
  42.     }  
  43.   
  44.     /** 
  45.      * 更新的时候 
  46.      */  
  47.     @Override  
  48.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  49.         db.execSQL("DROP TABLE IF EXISTS person");  
  50.         onCreate(db);  
  51.     }  
  52.   
  53. }  

 

PersonDao.java

Java代码   收藏代码
  1. package org.e276.dao;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import org.e276.entity.Person;  
  6. import android.content.Context;  
  7. import android.database.Cursor;  
  8. import android.database.sqlite.SQLiteDatabase;  
  9. /** 
  10.  * 实现类 
  11.  * @author miao 
  12.  * 
  13.  */  
  14. public class PersonDao {  
  15.   
  16.     // 辅助类属性  
  17.     private DBHelper helper;  
  18.   
  19.     /** 
  20.      * 带参构造方法,传入context 
  21.      *  
  22.      * @param context 
  23.      */  
  24.     public PersonDao(Context context) {  
  25.         helper = new DBHelper(context);  
  26.     }  
  27.   
  28.     /** 
  29.      * 使用不同的方法删除记录1到多条记录 
  30.      *  
  31.      * @param ids 
  32.      */  
  33.     public void delete(Integer... ids) {  
  34.         String[] c = new String[ids.length];  
  35.         StringBuffer sb = new StringBuffer();  
  36.         if (ids.length > 0) {  
  37.             for (int i = 0; i < ids.length; i++) {  
  38.                 sb.append('?').append(',');  
  39.                 // 把整数数组转换哼字符串数组  
  40.                 c[i] = ids[i].toString();  
  41.             }  
  42.             // 删除最后一个元素  
  43.             sb.deleteCharAt(sb.length() - 1);  
  44.         }  
  45.         SQLiteDatabase db = helper.getWritableDatabase();  
  46.         db.delete("person""personid in (" + sb.toString() + ")", c);  
  47.         db.close();  
  48.     }  
  49.   
  50.     /** 
  51.      * 添加纪录 
  52.      *  
  53.      * @param person 
  54.      */  
  55.     public void save(Person person) {  
  56.         SQLiteDatabase db = helper.getWritableDatabase();  
  57.         db.execSQL("insert into person (name,age) values(?,?)"new Object[] {  
  58.                 person.getName(), person.getAge() });  
  59.         db.close();  
  60.     }  
  61.   
  62.     /** 
  63.      * 根据id查找 
  64.      *  
  65.      * @param id 
  66.      * @return 
  67.      */  
  68.     public Person find(Integer id) {  
  69.         SQLiteDatabase db = helper.getWritableDatabase();  
  70.         Cursor cursor = db.rawQuery("select * from person where personid=?",  
  71.                 new String[] { String.valueOf(id) });  
  72.         if (cursor.moveToNext()) {  
  73.             return new Person(cursor.getInt(0), cursor.getString(1),  
  74.                     cursor.getInt(2));  
  75.         }  
  76.         return null;  
  77.     }  
  78.   
  79.     /** 
  80.      * 查找所有的记录 
  81.      *  
  82.      * @return 
  83.      */  
  84.     public List<Person> getAll() {  
  85.         List<Person> persons = new ArrayList<Person>();  
  86.         SQLiteDatabase db = helper.getReadableDatabase();  
  87.         Cursor cursor = db.rawQuery("select * from person"null);  
  88.         while (cursor.moveToNext()) {  
  89.             persons.add(new Person(cursor.getInt(0), cursor.getString(1),  
  90.                     cursor.getInt(2)));  
  91.         }  
  92.         return persons;  
  93.     }  
  94.   
  95.     /** 
  96.      * 查询全部 
  97.      *  
  98.      * @return 游标 
  99.      */  
  100.     public Cursor getAllPerson() {  
  101.         SQLiteDatabase db = helper.getReadableDatabase();  
  102.         // ListView 里的id是有个下划线的,所以这里要给个别名_id  
  103.         Cursor cursor = db.rawQuery(  
  104.                 "select personid as _id, name,age from person"null);  
  105.         // 这里数据库不能关闭  
  106.         return cursor;  
  107.     }  
  108.   
  109. }  

 

 

六、Activity类

Java代码   收藏代码
  1. package org.e276.db;  
  2.   
  3. import org.e276.dao.PersonDao;  
  4. import android.app.Activity;  
  5. import android.database.Cursor;  
  6. import android.database.sqlite.SQLiteCursor;  
  7. import android.os.Bundle;  
  8. import android.view.View;  
  9. import android.widget.AdapterView;  
  10. import android.widget.ListView;  
  11. import android.widget.SimpleCursorAdapter;  
  12. import android.widget.Toast;  
  13.   
  14. public class MainActivity extends Activity {  
  15.   
  16.     // 声明ListView对象  
  17.     private ListView listView;  
  18.   
  19.     // Dao  
  20.     private PersonDao personDao;  
  21.   
  22.     /** Called when the activity is first created. */  
  23.     @Override  
  24.     public void onCreate(Bundle savedInstanceState) {  
  25.         super.onCreate(savedInstanceState);  
  26.         setContentView(R.layout.main);  
  27.   
  28.         // 获得listview  
  29.         listView = (ListView) findViewById(R.id.listView);  
  30.         // 实例化dao  
  31.         personDao = new PersonDao(this);  
  32.         // 得到所有的记录  
  33.         Cursor cursor = personDao.getAllPerson();  
  34.   
  35.         /* 
  36.          * 参数作用:context:显示数据的layout,游标:显示的列名(一定要包含_id),显示的控件id名 
  37.          */  
  38.         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,  
  39.                 R.layout.person, cursor, new String[] { "_id""name""age" },  
  40.                 new int[] { R.id.id, R.id.name, R.id.age });  
  41.         listView.setAdapter(adapter);  
  42.   
  43.         listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
  44.   
  45.             public void onItemClick(AdapterView<?> parent, View view,  
  46.                     int position, long id) {  
  47.                 ListView lst = (ListView) parent;  
  48.                 // 得到其中的一行  
  49.                 SQLiteCursor cursor = (SQLiteCursor) lst  
  50.                         .getItemAtPosition(position);  
  51.                 Toast.makeText(MainActivity.this, cursor.getString(1) + "被选中",  
  52.                         Toast.LENGTH_SHORT).show();  
  53.             }  
  54.         });  
  55.     }  
  56.   
  57. }  

 

 

七、test类,导入JUnit3包

Java代码   收藏代码
  1. package org.e276.test;  
  2.   
  3. import java.util.List;  
  4. import java.util.Random;  
  5. import org.e276.dao.PersonDao;  
  6. import org.e276.entity.Person;  
  7. import android.database.Cursor;  
  8. import android.test.AndroidTestCase;  
  9. import android.util.Log;  
  10.   
  11. /** 
  12.  * 测试类 用的是JUnit3,用4可能会报错 
  13.  *  
  14.  * @author miao 
  15.  *  
  16.  */  
  17. public class TestPersonDao extends AndroidTestCase {  
  18.   
  19.     PersonDao personDao = new PersonDao(getContext());  
  20.   
  21.     @Override  
  22.     protected void setUp() throws Exception {  
  23.         personDao = new PersonDao(getContext());  
  24.     }  
  25.   
  26.     /** 
  27.      * 保存 
  28.      */  
  29.     public void testSave() {  
  30.         for (int i = 1; i <= 30; i++) {  
  31.             personDao.save(new Person(-1"用户" + i, new Random().nextInt(100)));  
  32.         }  
  33.     }  
  34.   
  35.     /** 
  36.      * 根据id查找 
  37.      */  
  38.     public void testFind() {  
  39.         Person person = personDao.find(1);  
  40.         Log.i("tag", person.toString());  
  41.     }  
  42.   
  43.     /** 
  44.      * 查找全部 集合 
  45.      */  
  46.     public void testFindAll() {  
  47.         List<Person> persons = personDao.getAll();  
  48.         for (Person person : persons) {  
  49.             Log.i("tag", person.toString());  
  50.         }  
  51.     }  
  52.   
  53.     /* 
  54.      * 使用命令行查看内嵌数据库 在DOS下输入adb shell,或在sdk下的adb.exe下输入该命令 
  55.      *  
  56.      * Sqliteman 这个工具,可以打开db文件 
  57.      */  
  58.   
  59.     /** 
  60.      * 查找全部 游标 
  61.      */  
  62.     public void testGetAll() {  
  63.         Cursor cursor = personDao.getAllPerson();  
  64.         while (cursor.moveToNext()) {  
  65.             StringBuffer sb = new StringBuffer();  
  66.             sb.append("ID:" + cursor.getInt(0));  
  67.             sb.append("\t用户名:" + cursor.getString(1));  
  68.             sb.append("\t年龄:" + cursor.getInt(2));  
  69.             Log.i("person", sb.toString());  
  70.         }  
  71.     }  
  72.       
  73.     /** 
  74.      * 测试删除多条记录 
  75.      */  
  76.     public void testDelete(){  
  77.         personDao.delete(2,5,9);  
  78.     }  
  79.   
  80. }  

 

测试时,先运行save方法,向数据库循环添加纪录


 

运行其他方法时,例如testFind(),可以在LogCat里查看得到,前提是添加过滤器。

 

 

八、查看添加了的数据,可以运行app直接查看,又可以在dos控制台下输入命令查看

使用dir命令查看目录结构,然后用cd 目录名进入该目录,直到找到sdk里面的adb.exe为止。

接着使用adb shell命令,打开,出现“#”号代表已经打开了该程序。

ls 代表查看目录。

.help代表查看帮助命令,.tables代表查看数据库的表。

出现sqlite的时候代表可以使用SQL查询语句,增删改都会对数据库产生作用。

 

命令参考图,来自度娘



查询的结果(控制台中出现乱码是正常的,并不影响真正的查询结果):


 

 

九、demo

http://dl.iteye.com/topics/download/1827129d-2c72-38a4-a6dd-e7f3d8eab35b

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值