
Android提供了4种数据存储技术,分别是SharedPreferences、Files、SQLite数据库和网络存储数据。(有的开发者认为使用ContentProvider也可以算是一种,但我觉得ContentProvider本质上还是用的sqlite,所以未将其纳入其中)
其中最常用的有这三种:SharedPreferences、Files、SQLite数据库。
下面我们分别来认识一下:
1、SharedPreferences
它的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息。
其存储位置在/data/data/<包名>/shared_prefs目录下。
SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。
它主要是通过键值对的方式来存储数据的,获取它的方式有两种:
1、getSharedPreferences():如果需要多个使用名称来区分的共享文件,则可以使用该方法,其第一个参数就是共享文件的名称。对于使用同一个名称获得的多个SharedPreferences引用,其指向同一个对象。
2、getPreferences();如果Activity仅需要一个共享文件,则可以使用该方法。因为只有一个文件,它并不需要提供名称。
完成SharedPreferences类中增加值的步骤如下:
- 调用SharedPreferences类的edit()方法获得SharedPreferences.Editor对象。
- 调用如putBoolean()、putString()等方法附加值
- 使用commit()方法提交新值。
SharedPreferences使用时,分两种:
一种是在一个项目中使用,另一个是在两个不同的项目中使用。
下面我们用实例来演示一下,首先是第一种情况(即在一个项目中使用):
首先是布局文件main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/name_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="姓名:"
android:textSize="30sp"/>
<EditText
android:id="@+id/ET_name"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="text"
android:textSize="20sp">
<requestFocus></requestFocus>
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tv_psd"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="密码:"
android:textSize="30sp"/>
<EditText
android:id="@+id/et_psd"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_width="0dip"
android:textSize="20sp"
android:inputType="textPassword"/>
</LinearLayout>
<Button
android:id="@+id/bt_login"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="登陆"
android:textSize="20sp"/>
</LinearLayout>
read_data.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tv_rname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"/>
<TextView
android:id="@+id/tv_rpsd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"/> </LinearLayout>
然后新建两个Activity,分别为ReadActivity和WriteActivity:
public class ReadActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.read_data);
TextView tv_name=(TextView) findViewById(R.id.tv_rname);
TextView tv_psd=(TextView) findViewById(R.id.tv_rpsd);
SharedPreferences sp=getSharedPreferences("test", MODE_PRIVATE);
tv_name.setText(sp.getString("name", "error_name"));
tv_psd.setText(sp.getString("psd", "error_psd"));
} }
public class WriteActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText et_name=(EditText) findViewById(R.id.ET_name);
final EditText et_psd=(EditText) findViewById(R.id.et_psd);
Button bt_login=(Button) findViewById(R.id.bt_login);
bt_login.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
String name=et_name.getText().toString();
String psd=et_psd.getText().toString();
SharedPreferences sp_login=getSharedPreferences("test", MODE_PRIVATE);
Editor editor=sp_login.edit();
editor.putString("name", name);
editor.putString("psd", psd);
editor.commit();
Intent intent=new Intent();
intent.setClass(WriteActivity.this, ReadActivity.class);
startActivity(intent); }
});
}
}
这里记得把配置文件也要修改一下(注册Activity和修改默认启动Activity):
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demo_base_sharedpreferences"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" /> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.demo_base_sharedpreferences.WriteActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.demo_base_sharedpreferences.ReadActivity"></activity>
</application> </manifest>
代码完毕,运行程序即可体验SharedPreferences在仅在一个项目中的使用情况。
下面来看看第二种(两个不同项目之间的使用),因为很多代码都是相同的,就直接上代码了:
创建第一个项目demo_between_SharedPreferences01
main布局文件代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="@+id/tv_read"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="全局可读:"
android:textSize="20sp"/>
<EditText
android:id="@+id/et_read"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="text"
android:textSize="20sp"/>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="@+id/tv_write"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="全局可写:"
android:textSize="20sp"/>
<EditText
android:id="@+id/et_write"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="text"
android:textSize="20sp"/>
</LinearLayout>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:id="@+id/tv_read_write"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="全局可读:"
android:textSize="20sp"/>
<EditText
android:id="@+id/et_read_write"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="text"
android:textSize="20sp"/>
</LinearLayout>
<Button
android:id="@+id/bt_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="保存键值对"
android:textSize="20sp"/>
</LinearLayout>
java文件:
private EditText et_read,et_write,et_read_write;
private SharedPreferences sp_read,sp_write,sp_read_write; @SuppressLint("WorldReadableFiles")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et_read=(EditText) findViewById(R.id.et_read);
et_write=(EditText) findViewById(R.id.et_write);
et_read_write=(EditText) findViewById(R.id.et_read_write);
sp_read=getSharedPreferences("read", MODE_WORLD_READABLE);
sp_write=getSharedPreferences("write", MODE_WORLD_WRITEABLE);
sp_read_write=getSharedPreferences("read_write", MODE_WORLD_READABLE+MODE_WORLD_WRITEABLE);
Button bt_save=(Button) findViewById(R.id.bt_save);
bt_save.setOnClickListener( save);
} public OnClickListener save=new OnClickListener() { @Override
public void onClick(View v) {
Editor ed_read=sp_read.edit();
Editor ed_write=sp_write.edit();
Editor ed_read_write=sp_read_write.edit();
ed_read.putString("test", et_read.getText().toString());
ed_write.putString("test", et_write.getText().toString());
ed_read_write.putString("test", et_read_write.getText().toString());
ed_read.commit();
ed_write.commit();
ed_read_write.commit(); }
};
创建第二个项目demo_between_SharedPreferences02
main.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="vertical" >
<TextView
android:id="@+id/read"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="30sp"/>
<TextView
android:id="@+id/write"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="30sp"/>
<TextView
android:id="@+id/read_write"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="30sp"/> </LinearLayout>
java文件
private SharedPreferences sp_read,sp_write,sp_read_write;
private TextView tv_read,tv_write,tv_read_write; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv_read=(TextView) findViewById(R.id.read);
tv_write=(TextView) findViewById(R.id.write);
tv_read_write=(TextView) findViewById(R.id.read_write);
Context othercontext=null;
try {
othercontext=createPackageContext("com.example.demo_between_sharepreferences", MODE_PRIVATE);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sp_read=othercontext.getSharedPreferences("read", MODE_WORLD_READABLE);
sp_write=othercontext.getSharedPreferences("write", MODE_WORLD_WRITEABLE);
sp_read_write=othercontext.getSharedPreferences("read_write", MODE_WORLD_READABLE+MODE_WORLD_WRITEABLE);
tv_read.setText("全局可读:"+sp_read.getString("test", "null"));
tv_write.setText("全局可写:"+sp_write.getString("test", "null"));
tv_read_write.setText("全局可读可写:"+sp_read_write.getString("test", "null")); }
然后运行第一个项目,输入信息,点击保存。
运行第二个项目。则界面上显示了用户刚刚在第一个项目中输入并保存的信息。
2、文件Files对象存储
在Android中,文件对象存储主要有两种方式:
- java提供的io流体系。(FileOutputStream类的openFileOutput()方法和FileInputStram类提供的openFileInput()方法)默认情况下,使用IO流保存的文件仅对当前应用程序可见。如果用户卸载了该应用程序,则保存数据的文件也会被一起删除。
- 使用Environment类的getExternalStorageDirectory()方法对Android中SD卡的操作。
对文件的操作呢,建议大家可以先看看它的相关文档,如我们会使用到的:
http://developer.android.com/intl/zh-cn/reference/java/io/File.html
接下来我们依然用实例来体验一下吧。
第一种使用java提供的io流体系
本实例的布局文件我们使用讲SharedPreferences的第一种情况时使用的布局文件。(注意:在控件的名称上可能会有改动)
然后创建两个Activity:InternalDataWriteActivity和InternalDataReadActivity:
public class InternalDataReadActivity extends Activity { protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // 调用父类方法
setContentView(R.layout.result);// 使用布局文件
FileInputStream fis = null;
byte[] buffer = null;
try {
fis = openFileInput("login");// 获得文件输入流
buffer = new byte[fis.available()];// 定义保存数据的数组
fis.read(buffer);// 从输入流中读取数据
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();// 关闭文件输入流
} catch (IOException e) {
e.printStackTrace();
}
}
} TextView usernameTV = (TextView) findViewById(R.id.username);
TextView passwordTV = (TextView) findViewById(R.id.password);
String data = new String(buffer);// 获得数组中保存的数据
String username = data.split(" ")[0];// 获得username
String password = data.split(" ")[1];// 获得password
usernameTV.setText("用户名:" + username);// 显示用户名
passwordTV.setText("密 码:" + password);// 显示密码
}
}
public class InternalDataWriteActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);// 调用父类方法
setContentView(R.layout.main);// 应用布局文件
final EditText usernameET = (EditText) findViewById(R.id.username);// 获得用户名控件
final EditText passwordET = (EditText) findViewById(R.id.password);// 获得密码控件
Button login = (Button) findViewById(R.id.login);// 获得按钮控件
login.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) {
String username = usernameET.getText().toString();// 获得用户名
String password = passwordET.getText().toString();// 获得密码
FileOutputStream fos = null;
try {
fos = openFileOutput("login", MODE_PRIVATE);// 获得文件输出流
fos.write((username + " " + password).getBytes());// 保存用户名和密码
fos.flush();// 清除缓存
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();// 关闭文件输出流
} catch (IOException e) {
e.printStackTrace();
}
}
}
Intent intent = new Intent();// 创建Intent对象
intent.setClass(InternalDataWriteActivity.this, InternalDataReadActivity.class);// 指定跳转到InternalDataReadActivity
startActivity(intent);// 实现跳转
}
});
}
}
最后注意配置文件的修改:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mingrisoft"
android:versionCode="1"
android:versionName="1.0" > <uses-sdk android:minSdkVersion="15" /> <application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name="com.mingrisoft.InternalDataWriteActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.mingrisoft.InternalDataReadActivity" />
</application> </manifest>
运行程序,输入数据后,跳转到另一个页面时读取第一个页面的数据。(当然,这种效果也可以使用SharedPreferences)
第二种对安卓的SD卡的操作
修改main.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:background="@drawable/background"
android:orientation="vertical" > <TextView
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:textSize="20dp" /> </LinearLayout>
然后创建一个Activity类:
public class FileCreateActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);// 调用父类方法
setContentView(R.layout.main);// 应用布局文件
TextView tv = (TextView) findViewById(R.id.message);
File root = Environment.getExternalStorageDirectory();// 获得SD卡根路径
if(root.exists()&&root.canWrite()){
File file = new File(root, "DemoFile.txt");
try {
if (file.createNewFile()) {
tv.setText(file.getName() + "创建成功!");
} else {
if(file.exists()){
file.delete();
tv.setText("已删除同名文件,请重新创建。");
}
else
tv.setText(file.getName() + "创建失败!"); } } catch (IOException e) {
e.printStackTrace();
}
}else {
tv.setText("SD卡不存在或者不可写!");
}
}
}
最后在配置文件中添加权限和修改默认Activity:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<activity
android:name="com.mingrisoft.FileCreateActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
此时,即可运行程序。
3、SQLite的数据库存储
Android系统自带有轻量级的数据库—SQLite。它与我们所接触其他数据库大部分都相同,支持大部分的标准SQL语句,分页查询和mysql相同:
select * from person(表名) LIMIT 10,20(第10条索引开始,取20条数据)。
另外,它还有个需要注意的地方,那就是不区分数据类型(主键除外)。
光说知识点比较空洞,下面我们用一个例子来认识sqlite,在例子中会用注释来解释一些sqlite的知识。
不多说直接上代码:
新建一个DBOpenHelper类,并继承SQLiteOpenHelper:
package cn.itcast.sqlite; import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper; public class DBOpenHelper extends SQLiteOpenHelper { // 定义工具类, 继承SQLiteOpenHelper public DBOpenHelper(Context context) { // 创建对象的时候, 需要传入上下文环境
super(context, "itcast.db", null, 4);
/*
* 由于父类没有无参构造函数, 必须显式调用有参的构造函数
* 参数1: 上下文环境, 用来确定数据库文件存储的目录
* 参数2: 数据库文件的名字
* 参数3: 生成游标的工厂, 填null就是使用默认的
* 参数4: 数据库的版本, 从1开始
*/
} @Override
public void onCreate(SQLiteDatabase db) {
System.out.println("onCreate");
db.execSQL("CREATE TABLE person(id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20))"); // 执行SQL语句, 创建表
} @Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println("onUpgrade");
db.execSQL("ALTER TABLE person ADD balance INTEGER");
} }
创建一个实体类person,接下来的例子中会使用到:
在创建时,get,set方法和一些构造函数可以通过选择菜单栏或点击鼠标右键出现的source选项中选择快速生成。
package cn.itcast.sqlite; public class Person {
private Integer id;
private String name;
private Integer balance; public Person() {
super();
} public Person(String name, Integer balance) {
super();
this.name = name;
this.balance = balance;
} public Person(Integer id, String name, Integer balance) {
super();
this.id = id;
this.name = name;
this.balance = balance;
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getBalance() {
return balance;
} public void setBalance(Integer balance) {
this.balance = balance;
} @Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", balance=" + balance + "]";
} }
下面创建一个操作sql语句的PersonDao类:
该类中,包含了最常用的sql语句,其中的注释的地方希望大家理解意思。
package cn.itcast.sqlite; import java.util.ArrayList;
import java.util.List; import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; public class PersonDao {
private DBOpenHelper helper; public PersonDao(Context context) {
helper = new DBOpenHelper(context);
} public void insert(Person p) {
SQLiteDatabase db = helper.getWritableDatabase(); // 获取数据库连接(可写的)
db.execSQL("INSERT INTO person(name, balance) VALUES(?, ?)", new Object[] { p.getName(), p.getBalance() }); // 执行SQL语句, 插入
db.close();
} public void delete(int id) {
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("DELETE FROM person WHERE id=?", new Object[] { id });
db.close();
} public void update(Person p) {
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("UPDATE person SET name=?, balance=? WHERE id=?", new Object[] { p.getName(), p.getBalance(), p.getId() });
db.close();
} public Person query(int id) {
SQLiteDatabase db = helper.getReadableDatabase(); // 获取数据库连接(可读的)
Cursor c = db.rawQuery("SELECT name, balance FROM person WHERE id=?", new String[] { id + "" }); // 执行SQL语句, 查询, 得到游标
Person p = null;
if (c.moveToNext()) { // 判断游标是否包含下一条记录, 如果包含将游标向后移动一位
String name = c.getString(c.getColumnIndex("name")); // 获取"name"字段的索引, 然后根据索引获取数据
int balance = c.getInt(1); // 获取1号索引上的数据
p = new Person(id, name, balance);
}
c.close();
db.close();
return p;
} public List<Person> queryAll() {
SQLiteDatabase db = helper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT id, name, balance FROM person", null);
List<Person> persons = new ArrayList<Person>();
while (c.moveToNext()) {
Person p = new Person(c.getInt(0), c.getString(1), c.getInt(2));
persons.add(p);
}
c.close();
db.close();
return persons;
} public int queryCount() {
SQLiteDatabase db = helper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT COUNT(*) FROM person", null);
c.moveToNext();
int count = c.getInt(0);
c.close();
db.close();
return count;
} public List<Person> queryPage(int pageNum, int capacity) {
String offset = (pageNum - 1) * capacity + ""; // 偏移量
String len = capacity + ""; // 个数
SQLiteDatabase db = helper.getReadableDatabase();
Cursor c = db.rawQuery("SELECT id, name, balance FROM person LIMIT ?,?", new String[]{offset , len});
List<Person> persons = new ArrayList<Person>();
while (c.moveToNext()) {
Person p = new Person(c.getInt(0), c.getString(1), c.getInt(2));
persons.add(p);
}
c.close();
db.close();
return persons;
} }
最后,我们将用单元测试类来检验我们做得是否正确(注意,不要忘记在配置文件中注册Junit的使用(详见《Android Junit单元测试》一文)):
package cn.itcast.sqlite; import java.util.List;
import java.util.Random; import android.test.AndroidTestCase; public class DBTest extends AndroidTestCase { public void testCreateDatabase() {
DBOpenHelper helper = new DBOpenHelper(getContext());
helper.getWritableDatabase();
/*
* 获取可写的数据连接
* 数据库文件不存在时, 会创建数据库文件, 并且执行onCreate()方法
* 数据库文件存在, 并且版本没有改变时, 不执行任何方法
* 数据库文件存在, 版本提升, 执行onUpgrade()方法
*/
} public void testInsert() {
PersonDao dao = new PersonDao(getContext());
for (int i = 1; i <= 100; i++)
dao.insert(new Person("Test" + i, new Random().nextInt(10000)));
} public void testDelete() {
PersonDao dao = new PersonDao(getContext());
dao.delete(1);
} public void testUpdate() {
PersonDao dao = new PersonDao(getContext());
dao.update(new Person(3, "王五", 30000));
} public void testQuery() {
PersonDao dao = new PersonDao(getContext());
System.out.println(dao.query(3));
} public void testQueryAll() {
PersonDao dao = new PersonDao(getContext());
List<Person> persons = dao.queryAll();
for (Person p : persons)
System.out.println(p);
} public void testQueryCount() {
PersonDao dao = new PersonDao(getContext());
System.out.println(dao.queryCount());
} public void testQueryPage() {
PersonDao dao = new PersonDao(getContext());
List<Person> persons = dao.queryPage(3, 20);
for (Person p : persons)
System.out.println(p);
} }
运行程序即可。(该例使用的是System.out输出结果,为方便查看建议add a new logcte filter)
上面是sqlite的最常规和最基本的操作。
下面我们来看看sqlite的一些其他操作:
1、数据库事务的操作。不多说,直接上代码:
在PersonDao类中,添加一个新的方法:(前两个参数代表的是数据库中的ID字段)
public void remit(int from, int to, int amount) {
SQLiteDatabase db = helper.getWritableDatabase();
try {
db.beginTransaction(); // 开始事务
db.execSQL("UPDATE person SET balance=balance-? WHERE id=?", new Object[] { amount, from });
db.execSQL("UPDATE person SET balance=balance+? WHERE id=?", new Object[] { amount, to });
db.setTransactionSuccessful(); // 设置成功点, 在事务结束时, 成功点之前的操作会被提交
/*若此处再接下面的三行代码
db.execSQL("……"); //如果此行的代码出现异常,那么上面的(即前面的)两个execSQL()执行的SQL语句可以正常执行,此行和下面的execSQL()将不会被执行。
db.execSQL("……"); //如果只有此行代码异常,那么最上面的(即前面的)两个execSQL()执行的SQL语句可以正常执行,此行和上面的execSQL()将不会被执行。
db.setTransactionSuccessful();
*/
} finally {
db.endTransaction(); // 结束事务, 将成功点之前的操作提交
db.close();
}
}
在DBtest单元测试类中,测试刚刚添加的有关事务的方法:
public void testRemit() {
PersonDao dao = new PersonDao(getContext());
dao.remit(3, 2, 1000);
}
2、另一种数据操作(增删查改)的方式
这种方式呢,不需要写SQL语句。但是,它的实质是转换成sql语句再执行。在某些情况下呢,对数据的操作会更加方便。
下面,我们就将PersonDao类用新的数据操作的方式来实现一下,大家可以对比一下与之前的PersonDao类的区别,其实真正关键的、不同的代码就那么几句,大部分还是相同的。
package cn.itcast.sqlite; import java.util.ArrayList;
import java.util.List; import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; public class PersonDao {
private DBOpenHelper helper; public PersonDao(Context context) {
helper = new DBOpenHelper(context);
} public void insert(Person p) {
SQLiteDatabase db = helper.getWritableDatabase(); // 获取数据库连接(可写的)
ContentValues values = new ContentValues(); // 类似于Map的容器, 键是String, 用来存放列名, 值是Object, 用来存要插入的数据
values.put("name", p.getName()); // 某些情况下, 程序会接收一个ContentValues参数, 这时用这种方式存储比较方便
values.put("balance", p.getBalance());
long id = db.insert("person", null, values); // 第二个参数随便写表中的一个列名即可, 用来在想插入一条除了主键全部为空的记录时使用
System.out.println("插入的记录的id是: " + id);
db.close();
} public void delete(int id) {
SQLiteDatabase db = helper.getWritableDatabase();
int rows = db.delete("person", "id=?", new String[] { id + "" });
System.out.println("删除了" + rows + "行");
db.close();
} public void update(Person p) {
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", p.getName());
values.put("balance", p.getBalance());
int rows = db.update("person", values, "id=?", new String[] { p.getId() + "" });
System.out.println("更新了" + rows + "行");
db.close();
} public Person query(int id) {
SQLiteDatabase db = helper.getReadableDatabase(); // 获取数据库连接(可读的)
Cursor c = db.query("person", new String[] { "name", "balance" }, "id=?", new String[] { id + "" }, null, null, null);
Person p = null;
if (c.moveToNext()) { // 判断游标是否包含下一条记录, 如果包含将游标向后移动一位
String name = c.getString(c.getColumnIndex("name")); // 获取"name"字段的索引, 然后根据索引获取数据
int balance = c.getInt(1); // 获取1号索引上的数据
p = new Person(id, name, balance);
}
c.close();
db.close();
return p;
} public List<Person> queryAll() {
SQLiteDatabase db = helper.getReadableDatabase();
Cursor c = db.query("person", null, null, null, null, null, "id DESC");
List<Person> persons = new ArrayList<Person>();
while (c.moveToNext()) {
Person p = new Person(c.getInt(0), c.getString(1), c.getInt(2));
persons.add(p);
}
c.close();
db.close();
return persons;
} public int queryCount() {
SQLiteDatabase db = helper.getReadableDatabase();
Cursor c = db.query("person", new String[]{ "COUNT(*)" }, null, null, null, null, null);
c.moveToNext();
int count = c.getInt(0);
c.close();
db.close();
return count;
} public List<Person> queryPage(int pageNum, int capacity) {
String offset = (pageNum - 1) * capacity + ""; // 偏移量
String len = capacity + ""; // 个数
SQLiteDatabase db = helper.getReadableDatabase();
Cursor c = db.query("person", null, null, null, null, null, null, offset + "," + len);
List<Person> persons = new ArrayList<Person>();
while (c.moveToNext()) {
Person p = new Person(c.getInt(0), c.getString(1), c.getInt(2));
persons.add(p);
}
c.close();
db.close();
return persons;
} public void remit(int from, int to, int amount) {
SQLiteDatabase db = helper.getWritableDatabase();
try {
db.beginTransaction(); // 开始事务
db.execSQL("UPDATE person SET balance=balance-? WHERE id=?", new Object[] { amount, from });
db.execSQL("UPDATE person SET balance=balance+? WHERE id=?", new Object[] { amount, to });
db.setTransactionSuccessful(); // 设置成功点, 在事务结束时, 成功点之前的操作会被提交
} finally {
db.endTransaction(); // 结束事务, 将成功点之前的操作提交
db.close();
}
} }