一.SQLite数据库:
SQLite第一个 Alpha版本诞生于2000年5月,是一款轻型数据库,设计目的是嵌入式的,它占用的资源非常少,在嵌入式的设备中只需要几百KB就足够了,这也就是android系统使用SQLite的原因。
SQLite数据库具有如下特征:
1.轻量级:
SQLite和C/S模式(Client/Server,客户机/服务器)的数据库软件不同,他是进程内的数据库引擎,因此不存在数据库的客户端和服务器。使用SQLite一般只需要带上他的一个动态库,就可以使用他的全部功能,并且动态库也非常小。
2.独立性:
SQLite数据库的核心引擎本身不依赖第三方软件,使用他也不需要“安装”,所以在部署时能省去不少的麻烦。
3.隔离性:
SQLite数据库中的所有信息都包含在一个文件内,方便管理和维护。
4.跨平台:
SQLite数据库支持大部分操作系统,除了我们在电脑上使用的操作系统之外,很多手机操作系统都可以运行,例如Android、Windows Mobile等。
5.多语言接口:
SQLite数据库支持很多语言编程接口,比如java、python、doNet等。
6.安全性:
SQLite数据库通过数据库级上的独占性和共享锁来实现独立事物处理。这意味着多个进程可以在同一时间从同一数据库读取数据,但只有一个可以写入数据,在某个进程或线程向数据库执行写入操作之前,必须获得独占锁定,在发出独占锁定后,其他的读或写操作将不会再发生。
以上内容摘自<Android应用开发揭秘>杨丰盛 著。
二.SQLite操作:
SQLite一般数据库操作:创建数据库、打开数据库、创建表、向表中添加数据、从表中删除数据、修改表中数据、关闭数据库、删除指定表、删除数据库和查询表中的莫条数据。
我一下内容都是由单元测试实现:
在使用android单元测试的时候一定要在清单文件中添加我的清单文件:
1.创建数据库(lzr.db)和表(person):
public class DBOpenHelper extends SQLiteOpenHelper { //删除后面的三个参数,我们自己内部设定,以后条件改变在进行修改 public DBOpenHelper(Context context) { //第二个参数 执行数据库的名称.第三个参数游标工厂我们传null表示使用系统默认的. //第四个参数我们表示为数据库版本号(大于0任何数都可以)。 super(context, "lzr.db",null, 1); //数据库保存在<包>/database/ } //SQLiteDatabase中封装了数据库的所有操作。 @Override public void onCreate(SQLiteDatabase db) {//数据库第一次被创建的时候被调用 // TODO Auto-generated method stub db.execSQL("CREATE TABLE person(personid integer primary key autoincrement,name varchar(20),phone VARCHAR(12) NULL)"); } //此方法是在数据库的版本号发生变更的时候被调用。 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub db.execSQL("ALTER TABLE person ADD amount integer"); } }
这里我们继承SQLiteOpenHelper,当我们创建这个类的实例时,会创建数据库,我们调用父类的构造方法,就能创建出一个数据库,数据库的名称lzr.db,当数据库第一次被创建时,会自动的调用onCreate方法,我们在这个方法中一般放入的是表的创建语句。这里的数据库语句就是sql语句,我们设置personid为主键自动增长。
当我们修改了构造方法中的数据库版本号,这个版本号不能小于且等于零。
当我们第一次版本号为1的时候:
当修改了数据库版本号时,再次构造此类的对象则会触发onUpgrade()方法:
2.表的操作:
创建一个实体类:
public class Person { private int id ; private String name; private String phone; private Integer amount; public Integer getAmount() { return amount; } public void setAmount(Integer amount) { this.amount = amount; } public Person(){} public Person(String name) { this.name = name; } public Person(String name, String phone){ this.name = name; this.phone = phone; } public Person(String name, String phone,Integer amount) { this.name = name; this.phone = phone; this.amount = amount; } public Person(int id, String name, String phone,Integer amount) { this.id = id; this.name = name; this.phone = phone; this.amount = amount; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { // TODO Auto-generated method stub return this.id+" "+this.name+" "+this.phone+" "+this.amount; } }
创建一个业务类:
public class PersonService { private DBOpenHelper dbo; public PersonService(Context context){ this.dbo = new DBOpenHelper(context); } /** * 添加记录 * @param person */ public void addPerson(Person person){ SQLiteDatabase sql = dbo.getWritableDatabase(); sql.execSQL("insert into person(name,phone,amount) values(?,?,?)",new Object[]{person.getName(),person.getPhone(),person.getAmount()}); } /** * 删除记录 * @param id */ public void deletePerson(Integer id){ SQLiteDatabase sql = dbo.getWritableDatabase(); sql.execSQL("delete from person where personid=?",new Object[]{id}); } /** * 修改记录 * @param person */ public void updatePerson(Person person){ SQLiteDatabase sql = dbo.getWritableDatabase(); sql.execSQL("update person set name=?,phone=?,amount=? where personid=?",new Object[]{person.getName(),person.getPhone(),person.getAmount(),person.getId()}); } /** * 查找记录 * @param id * @return */ public Person find(Integer id){ SQLiteDatabase sql = dbo.getReadableDatabase(); Cursor cu = sql.rawQuery("select * from person where personid=?", new String[]{id.toString()}); if(cu.moveToFirst()){ int personid = cu.getInt(cu.getColumnIndex("personid")); String name = cu.getString(cu.getColumnIndex("name")); String phone = cu.getString(cu.getColumnIndex("phone")); int amount = cu.getInt(cu.getColumnIndex("amount")); return new Person(personid,name,phone,amount); } cu.close(); return null; } /** * 分页获取记录 * @param offset 跳过前面多少条记录 * @param maxResult 每页获取多少条记录 * @return */ public List<Person> getListPerson(int offset,int maxResult){ List<Person> list = new ArrayList<Person>(); SQLiteDatabase sql = dbo.getReadableDatabase(); Cursor cu = sql.rawQuery("select * from person order by personid asc limit ?,?", new String[]{String.valueOf(offset),String.valueOf(maxResult)}); while(cu.moveToNext()){ int personid = cu.getInt(cu.getColumnIndex("personid")); String name = cu.getString(cu.getColumnIndex("name")); String phone = cu.getString(cu.getColumnIndex("phone")); int amount = cu.getInt(cu.getColumnIndex("amount")); System.out.println(name); list.add(new Person(personid,name,phone,amount)); } cu.close(); return list; } /** * 获取 * @return */ public Long getCount(){ SQLiteDatabase sql = dbo.getReadableDatabase(); Cursor cu = sql.rawQuery("select count(*) from person ", null); cu.moveToFirst(); long result = cu.getLong(0); cu.close(); return result; } public void payment(){ SQLiteDatabase sql = dbo.getWritableDatabase(); sql.beginTransaction();//开启事务 try{ sql.execSQL("update person set amount=amount-10 where personid=3"); sql.execSQL("update person set amount=amount+10 where personid=4"); sql.setTransactionSuccessful();//设置事务的标志为true。 }finally{ sql.endTransaction();//结束事物,有两种情况:commit,rollback //事物的提交或回滚是由事物的标志决定,如果事务的标志为true,事务就会提交,否则回滚,默认情况下事务的标志为false。 } } }
Cursor类常见方法:
1.move() 以当前位置为参考,将Cursor移动到指定的位置,成功返回true,失败返回false。
2.moveToPosition() 将Cursor移动到指定的位置,成功返回true,失败返回false。
3.moveToNext() 将Cursor向前移动一个位置,成功返回true,失败返回false。
4.moveToLast() 将Cursor向后移动一个位置,成功返回true,失败返回false。
5.moveToFirst() 将Cursor移动到第一行,成功返回true,失败返回false。
6.isBeforeFirst() 返回Cursor是否指向第一项数据之前。
7.isAfterLast() 返回Cursor时候指向最后一项数据之后。
8.isClosed() 返回Cursor是否关闭
9.isFirst() 返回Cursor是否指向第一项数据
10.isLast() 返回Cursor是否指向最后一项数据
11.isNull() 返回指定位置的值是否为NULL.
12.getCount() 返回总的数据项数。
13.getInt() 返回当前行中指定索引的数据。
单元测试类:
public class DBTest extends AndroidTestCase { public void testCreateDB() throws Exception{ DBOpenHelper d = new DBOpenHelper(getContext()); d.getWritableDatabase(); } public void testAddPerson() throws Exception{ PersonService per = new PersonService(this.getContext()); for(int i = 0; i < 15;i++){ Person person = new Person("lisi"+i,"123132131",200+i); per.addPerson(person); } } public void testDelete() throws Exception{ PersonService per = new PersonService(this.getContext()); per.deletePerson(2); } public void testUpdate() throws Exception{ PersonService per = new PersonService(this.getContext()); Person person = per.find(1); person.setName("wangwu"); per.updatePerson(person); } public void testFind() throws Exception{ PersonService per = new PersonService(this.getContext()); Person person = per.find(1); System.out.println(person.toString()); } public void testListPerson() throws Exception{ PersonService per = new PersonService(this.getContext()); //从0开始每页五条记录 List<Person> list = per.getListPerson(0, 5); for(Person person:list){ System.out.println(person); } } public void testCount() throws Exception{ PersonService per = new PersonService(this.getContext()); long result = per.getCount(); System.out.println(result); } public void testPayment(){ PersonService per = new PersonService(this.getContext()); per.payment(); Person person = per.find(3); Person person2 = per.find(4); System.out.println(person.toString()); System.out.println(person2.toString()); } }
testAddPerson()运行后数据库:
testUpdate()方法运行图片:
testDelete()方法运行图片:
testFind()方法运行图片:
testPayment()方法运行图片:
当我们想在模拟器上显示出数据时,可以用ListView来显示所有的数据:
ListView绑定的布局(item.xml):
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" > <TextView android:layout_width="90dp" android:layout_height="wrap_content" android:id="@+id/name" /> <TextView android:layout_width="140dp" android:layout_height="wrap_content" android:id="@+id/phone" /> <TextView android:layout_width="90dp" android:layout_height="wrap_content" android:id="@+id/amount" /> </LinearLayout>
主界面布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:layout_width="90dp" android:layout_height="wrap_content" android:text="姓名" /> <TextView android:layout_width="140dp" android:layout_height="wrap_content" android:text="电话" /> <TextView android:layout_width="90dp" android:layout_height="wrap_content" android:text="存款" /> </LinearLayout> <ListView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/listView" /> </LinearLayout>
这里我们有需要适配器,自定义适配器(PersonAdapter.java):
public class PersonAdapter extends BaseAdapter { private List<Person> persons ; //在绑定的数据 private int resource;//绑定的条目界面 private LayoutInflater inflater; public PersonAdapter(Context context ,List<Person> persons,int resource){ this.persons = persons; this.resource = resource; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } //返回绑定数据长度 @Override public int getCount() { return persons.size(); } @Override public Object getItem(int arg0) { return persons.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { TextView nameView = null; TextView phoneView = null; TextView amountView = null; if(arg1 == null){ arg1 = inflater.inflate(resource, null); nameView = (TextView)arg1.findViewById(R.id.name); phoneView = (TextView)arg1.findViewById(R.id.phone); amountView = (TextView)arg1.findViewById(R.id.amount); ViewCache cache = new ViewCache(); cache.nameView = nameView; cache.phoneView = phoneView; cache.amountView = amountView; arg1.setTag(cache); }else{ ViewCache vc = (ViewCache)arg1.getTag(); nameView = vc.nameView; phoneView = vc.phoneView; amountView = vc.amountView; } Person person = persons.get(arg0); nameView.setText(person.getName()); phoneView.setText(person.getPhone()); amountView.setText(String.valueOf(person.getAmount())); return arg1; } public final class ViewCache{ public TextView nameView; public TextView phoneView; public TextView amountView; } }
主代码:
public class MainActivity extends Activity { private ListView listview; private PersonService ps; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ps = new PersonService(this); listview = (ListView)findViewById(R.id.listView); listview.setOnItemClickListener(new ItemClickListener()); show2(); } private final class ItemClickListener implements OnItemClickListener{ @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) { ListView lv = (ListView)arg0; Person person = (Person)lv.getItemAtPosition(arg2); Toast.makeText(getApplicationContext(), String.valueOf(person.getId()), Toast.LENGTH_SHORT).show(); } } /** * 不使用自定义适配器显示效果。 public void show(){ List<Person> list = ps.getListPerson(0, 17); List<HashMap<String,Object>> data = new ArrayList<HashMap<String,Object>>(); for(Person person : list){ HashMap<String,Object> item = new HashMap<String, Object>(); item.put("name", person.getName()); item.put("phone",person.getPhone()); item.put("amount",person.getAmount()); item.put("id", person.getId()); data.add(item); } SimpleAdapter adapter = new SimpleAdapter(this, data, R.layout.item, new String[]{"name","phone","amount"},new int[]{R.id.name,R.id.phone,R.id.amount}); listview.setAdapter(adapter); } **/ public void show2(){ List<Person> persons = ps.getListPerson(0, 17); PersonAdapter pa = new PersonAdapter(this,persons,R.layout.item); listview.setAdapter(pa); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
运行界面:
android基础入门SQLite数据库操作(15),布布扣,bubuko.com
原文:http://blog.csdn.net/u010708662/article/details/22643041