SQLite,是一款轻型的数据库,占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。在android端时常会有运用,也是作为新手入门的必经之路,今天呢就给大家分享下关于SQLite一些简单操作。以一个实例为主。由于没有使用SQLiteOpenHelper类, 因此,您需要掌握一定的sql语句。
目的:掌握基于SQLite数据库的应用开发过程。
实例要求:建立一个通讯簿,可以向前向后浏览数据记录,也可以添加、修改、删除数据。
完成效果图:
代码分析
本人将代码主要为两个类:一个工具类DatabaseUtils、一个主界面入口类MainActivity
DatabaseUtils集成了各类关于SQLite的操作,简洁没有过多的废话,具体代码:
public class DatabaseUtils {
public static final String DBNAME = "mydb.db";
public static final String TNAME = "AddressBook";
private Context context;
private SQLiteDatabase db;
public static final String SQL_CT = "create table AddressBook(id INTEGER PRIMARY KEY,name,phone,address,email)";
public static String SQL_UP(String tag, String value, String id) {
String sql = "update AddressBook set " + tag + "='" + value
+ "' where id = " + id;
return sql;
}
public DatabaseUtils(Context context) {
this.context = context;
}
public void openDatabase() {
db = context.openOrCreateDatabase(DBNAME, context.MODE_PRIVATE, null);
}
public void create(String sql) {//创建数据库
db.beginTransaction();
db.execSQL(sql);
db.setTransactionSuccessful();
db.endTransaction();
}
public void insert(String sql) {//插入
db.beginTransaction();
db.execSQL(sql);
db.setTransactionSuccessful();
db.endTransaction();
}
public void update(String sql) {//更新
db.beginTransaction();
db.execSQL(sql);
db.setTransactionSuccessful();
db.endTransaction();
}
public void delect(String sql) {//删除
db.beginTransaction();
db.execSQL(sql);
db.setTransactionSuccessful();
db.endTransaction();
}
public Cursor query2(String sql) {//查询2 返回一个游标
db.beginTransaction();
Cursor cursor = db.rawQuery(sql, null);
db.setTransactionSuccessful();
db.endTransaction();
return cursor;
}
/** * 判断数据表是否存在 * @param tableName * @return */
public boolean isExsit(String tableName) {
boolean result = false;
if (tableName == null) {
return false;
}
Cursor cursor = null;
try {
String sql = "select count(*) as c from sqlite_master where type ='table' and name ='"
+ tableName.trim() + "' ";
cursor = db.rawQuery(sql, null);
if (cursor.moveToNext()) {
int count = cursor.getInt(0);
if (count > 0) {
result = true;
}
}
} catch (Exception e) {
// TODO: handle exception
}
return result;
}
public void closeDB() {//关闭数据库,打开数据库一定要记得关闭
db.close();
}
public int getCount(){//得到有多少条记录
String sql = "select id from AddressBook order by id desc limit 1";
int count = 1;
Cursor c = query2(sql);
while(c.moveToNext()){
count = Integer.valueOf(c.getString(0));
}
return count;
}
}
MainActivity类的实现,由于没什么过多的业务逻辑,因此一些逻辑直接在主函数中实现:
public class MainActivity extends Activity {
private EditText username, phone, address, email;
private DatabaseUtils dbUtils;
private int curID = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
initDatabase();
}
/** * 初始化数据库 */
private void initDatabase() {
dbUtils = new DatabaseUtils(this);
dbUtils.openDatabase();
if (!dbUtils.isExsit(DatabaseUtils.TNAME)) {
dbUtils.create(DatabaseUtils.SQL_CT);
}
dbUtils.closeDB();
}
private void init() {
username = (EditText) findViewById(R.id.et_username);
phone = (EditText) findViewById(R.id.et_phone);
address = (EditText) findViewById(R.id.et_address);
email = (EditText) findViewById(R.id.et_email);
}
public void bn_previous(View v) {
if (curID == 1) {
// updateShow(curID);
toast("已经是第一个。");
} else {
curID--;
updateShow(curID);
}
}
public void bn_next(View v) {
dbUtils.openDatabase();
System.out.println(dbUtils.getCount());
if (curID == (dbUtils.getCount())) {
toast("已经是最后一个。");
} else {
curID++;
updateShow(curID);
}
dbUtils.closeDB();
}
public void bn_add(View v) {
String u = username.getText().toString().trim();
String p = phone.getText().toString().trim();
String a = address.getText().toString().trim();
String e = email.getText().toString().trim();
if (checkInfo(u, p, a, e)) {
dbUtils.openDatabase();
String sql = "insert into AddressBook(name,phone,address,email) values('"
+ u + "','" + p + "','" + a + "','" + e + "')";
dbUtils.insert(sql);
toast("添加成功!");
dbUtils.closeDB();
} else {
toast("请填写 完整信息!");
}
}
public void bn_update(View v) {
String u = username.getText().toString().trim();
String p = phone.getText().toString().trim();
String a = address.getText().toString().trim();
String e = email.getText().toString().trim();
if (checkInfo(a, p, a, e)) {
dbUtils.openDatabase();
String sql = "update AddressBook set name = '" + u + "',phone = '"
+ p + "',address = " + "'" + a + "',email = '" + e
+ "' where id = " + curID;
dbUtils.update(sql);
toast("更新成功!");
dbUtils.closeDB();
} else {
toast("更新失败,信息不完整!");
}
}
public void bn_del(View v) {
String u = username.getText().toString().trim();
String p = phone.getText().toString().trim();
String a = address.getText().toString().trim();
String e = email.getText().toString().trim();
if (checkInfo(a, p, a, e)) {
dbUtils.openDatabase();
String sql = "delete from AddressBook where id = " + curID;
dbUtils.delect(sql);
toast("删除成功!");
username.setText("");
phone.setText("");
address.setText("");
email.setText("");
dbUtils.closeDB();
}
}
public void bn_close(View v) {
System.exit(0);
}
public void toast(String s) {
Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}
// 更新 当前窗口的显示
private void updateShow(int curID) {
dbUtils.openDatabase();
Cursor c = dbUtils.query2("select * from AddressBook where id = " + curID);
while (c.moveToNext()) {
String n = c.getString(1);
String p = c.getString(2);
String a = c.getString(3);
String e = c.getString(4);
username.setText(n);
phone.setText(p);
address.setText(a);
email.setText(e);
}
c.close();
dbUtils.closeDB();
}
/** * 检查填写的 内容 是否 完整 * * @param name * @param phone * @param address * @param email * @return */
private boolean checkInfo(String name, String phone, String address,
String email) {
if (name.isEmpty() || phone.isEmpty() || address.isEmpty()
|| email.isEmpty()) {
return false;
} else
return true;
}
}
接下来实现界面的xml布局,UI比较简单,利用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="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="horizontal" >
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="浏览通讯录:" />
<Button android:id="@+id/bn_previous" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="bn_previous" android:text="上一记录" />
<Button android:id="@+id/bn_next" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="bn_next" android:text="下一记录" />
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="horizontal" >
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="用户姓名:" />
<EditText android:id="@+id/et_username" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/bg" android:padding="5dp" />
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="horizontal" >
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="联系电话:" />
<EditText android:id="@+id/et_phone" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/bg" android:padding="5dp" />
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="horizontal" >
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="家庭地址:" />
<EditText android:id="@+id/et_address" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/bg" android:padding="5dp" />
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="horizontal" >
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="电子信箱:" />
<EditText android:id="@+id/et_email" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/bg" android:padding="5dp" />
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:orientation="horizontal" >
<Button android:id="@+id/bn_add" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="bn_add" android:text="添加" />
<Button android:id="@+id/bn_update" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="bn_update" android:text="修改" />
<Button android:id="@+id/bn_del" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="bn_del" android:text="删除" />
<Button android:id="@+id/bn_close" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="bn_del" android:text="关闭通讯录" />
</LinearLayout>
</LinearLayout>
代码块以贴出,你可以动手实现下,当然建议自己想着做出来,然后再来与我的进行对比,从中发现优缺点,欢迎给出评价
具体工程下载:下载请点击