Android数据库编程SQLite详解

参考: http://www.ataaw.com/?p=322
程序开发离不开数据库,数据库作为一种不可或缺的存储技术,同样的,在Android中也为我们提供了数据库支持,使用的是SQLite数据库系统。


SQLite是一种轻型数据库系统,并以嵌入式为设计目标,占用资源低,因此作为手机操作系统优秀的数据库系统选择平台。

SQLite的使用涉及两个重要的类,一个是SQLiteOpenHelper和SQLiteDatabase,SQLiteOpenHelper是SQLite的数据库辅助类,而SQLiteDatabase作为SQLite的数据库实体类,用于管理数据库增删改查等操作,下面我们详细解析SQLite的具体使用方法。

public class DatabaseHelper extends SQLiteOpenHelper { 
DatabaseHelper(Context context, String name, CursorFactory cursorFactory, int version) { 
        super(context, name, cursorFactory, version); 
    } 
@Override 
public void onCreate(SQLiteDatabase db) { 
        // 创建数据库后,对数据库的操作 
    } 
@Override 
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 
        // 更改数据库版本的操作 
    } 
@Override 
public void onOpen(SQLiteDatabase db) { 
        super.onOpen(db); 
        // 打开数据库后首先被执行 
    } 
}


让DatabaseHelper继承SQLiteOpenHelper,分别覆盖onCreate、onUpgrade和onOpen方法,这样在数据库的具体操作的时候,我们可以轻易获取数据库实例对象,具体应用我们继续分析以下代码,我们先来创建数据库。

private static final String DATABASE_NAME = "ataawcom.db"; //定义数据库名称 
private static final int DATABASE_VERSION = 1;//定义数据库版本 
private static final String TABLE_NAME = "ataaw";//定义数据表名称

DatabaseHelper dbHelper = new DatabaseHelper(this, DATABASE_NAME, null, 
                DATABASE_VERSION);//通过DatabaseHelper定义数据库


创建数据表:

void CreateTable() { 
SQLiteDatabase db = dbHelper.getWritableDatabase(); 
String sql = "CREATE TABLE IF NOT EXISTS " + TABLE_NAME 
    + " (ID INTEGER PRIMARY KEY, Name VARCHAR, Password VARCHAR);"; 
    try { 
        db.execSQL(sql); 
        } catch (SQLException ex) {//异常处理 
    } 
}


插入数据信息:

private void insert() { 
SQLiteDatabase db = dbHelper.getWritableDatabase(); 
try { 
    String sql = "insert into " + TABLE_NAME 
            + " (name, age) values (‘ATAAW’,'ATAAW.COM’)"; 
    db.execSQL(sql);//执行指定的 sql 
    } catch (SQLException ex) { 
        txtMsg.setText("插入数据失败\n" + ex.toString() + "\n"); 
    } 
}


删除数据:

private void delete() { 
try { 
    SQLiteDatabase db = dbHelper.getWritableDatabase(); 
    db.delete(TABLE_NAME, " id=1", null); 
     } catch (SQLException e) {//异常处理 
    } 
}


更新数据信息:

private void update() { 
SQLiteDatabase db = dbHelper.getWritableDatabase(); 
try { 
    ContentValues values = new ContentValues(); 
    values.put("name", "ataaw.com"); 
    db.update(TABLE_NAME, values, "id<=?", new String[] { "3" }); 
     } catch (SQLException e) {//异常处理 
   } 
}


删除数据表:

private void dropTable() { 
    SQLiteDatabase db = dbHelper.getWritableDatabase(); 
    String sql = "DROP TABLE IF EXISTS " + TABLE_NAME; 
    try { 
        db.execSQL(sql); 
    } catch (SQLException ex) {//异常处理 
    } 
}


有以上实例可以完成Android平台下数据库SQLite的基本数据库操作方法,我们可以看出与其他数据库操作的方法基本一样,通过SQL命令语句即可完成SQLite的各种操作,实现起来非常方便。



我的例子源代码:
string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">我的数据库操作例子</string>
    <string name="app_name">操作数据库</string>
    
    <string name="createDb_success">创建数据库成功</string>
    <string name="deleteDb_success">删除数据库成功</string>
    <string name="createTable_success">创建表成功</string>
    <string name="deleteTable_success">删除表成功</string>
    <string name="insert_success">插入数据成功</string>
    <string name="update_success">修改数据成功</string>
    <string name="delete_success">删除数据成功</string>
    <string name="select_success">查询成功</string>
    
    <string name="createDb_failure">创建数据库失败</string>
    <string name="deleteDb_failure">删除数据库失败</string>
    <string name="createTable_failure">创建表失败</string>
    <string name="deleteTable_failure">删除表失败</string>
    <string name="insert_failure">插入数据失败</string>
    <string name="update_failure">修改数据失败</string>
    <string name="delete_failure">删除数据失败</string>
    <string name="select_failure">查询失败</string>

</resources>


main.xml
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="@+id/widget36"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<TextView
android:id="@+id/widget32"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:layout_x="0px"
android:layout_y="0px"
>
</TextView>

<Button
    android:id="@+id/bt_createDB"
    android:layout_width="142dp"
    android:layout_height="wrap_content"
    android:layout_x="8dp"
    android:layout_y="23dp"
    android:text="创建数据库" />

<Button
    android:id="@+id/bt_deleteDB"
    android:layout_width="142dp"
    android:layout_height="wrap_content"
    android:layout_x="166dp"
    android:layout_y="22dp"
    android:text="删除数据库" />

<Button
    android:id="@+id/bt_createTable"
    android:layout_width="142dp"
    android:layout_height="wrap_content"
    android:layout_x="8dp"
    android:layout_y="78dp"
    android:text="创建表" />

<Button
    android:id="@+id/bt_deleteTable"
    android:layout_width="142dp"
    android:layout_height="wrap_content"
    android:layout_x="166dp"
    android:layout_y="78dp"
    android:text="删除表" />

<Button
    android:id="@+id/bt_insert"
    android:layout_width="80dp"
    android:layout_height="wrap_content"
    android:layout_x="2dp"
    android:layout_y="153dp"
    android:text="新增" />

<Button
    android:id="@+id/bt_update"
    android:layout_width="80dp"
    android:layout_height="wrap_content"
    android:layout_x="80dp"
    android:layout_y="151dp"
    android:text="修改" />

<Button
    android:id="@+id/bt_delete"
    android:layout_width="80dp"
    android:layout_height="wrap_content"
    android:layout_x="159dp"
    android:layout_y="152dp"
    android:text="删除" />

<Button
    android:id="@+id/bt_select"
    android:layout_width="80dp"
    android:layout_height="wrap_content"
    android:layout_x="237dp"
    android:layout_y="152dp"
    android:text="查询" />

<TextView
    android:id="@+id/vt_info"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:layout_x="6dp"
    android:layout_y="325dp"
    android:text="Inf......" />

<TextView
    android:id="@+id/widget41"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_x="10dp"
    android:layout_y="249dp"
    android:text="ID:" />

<EditText
    android:id="@+id/et_id"
    android:layout_width="82dp"
    android:layout_height="42px"
    android:layout_x="30dp"
    android:layout_y="236dp"
    android:textSize="12sp" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/et_name"
    android:layout_width="130dp"
    android:layout_height="42px"
    android:layout_x="185dp"
    android:layout_y="235dp"
    android:textSize="12sp" />

<TextView
    android:id="@+id/widget43"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_x="157dp"
    android:layout_y="246dp"
    android:text="名字:" />

</AbsoluteLayout>


java代码:
package com.db;

import java.util.Date;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursorDriver;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteQuery;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class DatabaseActivity extends Activity {
	private Button bt_createDB;
	private Button bt_deleteDB;
	private Button bt_createTable;
	private Button bt_deleteTable;
	private Button bt_insert;
	private Button bt_update;
	private Button bt_delete;
	private Button bt_select;
	private TextView vt_info;
	private EditText et_id;
	private EditText et_name;
	private String databaseNama="DatabaseText.db";
	private String tableNama="TestTable";
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        bt_createDB = (Button)findViewById(R.id.bt_createDB);
        bt_deleteDB = (Button)findViewById(R.id.bt_deleteDB);
        bt_insert = (Button)findViewById(R.id.bt_insert);
        bt_update = (Button)findViewById(R.id.bt_update);
        bt_delete = (Button)findViewById(R.id.bt_delete);
        bt_select = (Button)findViewById(R.id.bt_select);
        bt_createTable = (Button)findViewById(R.id.bt_createTable);
        bt_deleteTable = (Button)findViewById(R.id.bt_deleteTable);
        
        bt_createDB.setOnClickListener(new CreateDbOnClickListener());
        bt_deleteDB.setOnClickListener(new DeleteDbOnClickListener());
        bt_createTable.setOnClickListener(new CreateTableOnClickListener());
        bt_deleteTable.setOnClickListener(new DeleteTableOnClickListener());
        bt_insert.setOnClickListener(new InsertRecordOnClickListener());
        bt_update.setOnClickListener(new UpdateRecordOnClickListener());
        bt_delete.setOnClickListener(new DeleteRecordOnClickListener());
        bt_select.setOnClickListener(new SelectRecordOnClickListener());
        
        vt_info = (TextView)findViewById(R.id.vt_info);
        et_id = (EditText)findViewById(R.id.et_id);
        et_name = (EditText)findViewById(R.id.et_name);
    }
    class CreateDbOnClickListener implements View.OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			SQLiteDatabase db = null;
			try {
				
				db = DatabaseActivity.this.openOrCreateDatabase(databaseNama, DatabaseActivity.MODE_PRIVATE, new CursorFactory(){
					@Override
					public Cursor newCursor(SQLiteDatabase db,
							SQLiteCursorDriver masterQuery, String editTable,
							SQLiteQuery query) {
						// TODO Auto-generated method stub
						return null;
					}
					
				});
				vt_info.setText(getString(R.string.createDb_success));
			} catch (Exception e) {
				// TODO: handle exception
				vt_info.setText(e.getMessage());
			}finally{
				if(db!=null) db.close();
			}
			
			
		}
    	
    }
    class DatabaseUtils {
		public SQLiteDatabase getDatabase() {
			SQLiteDatabase db = null;
			try {
				db = DatabaseActivity.this.openOrCreateDatabase(databaseNama,
						DatabaseActivity.MODE_PRIVATE, new CursorFactory() {
							@Override
							public Cursor newCursor(SQLiteDatabase db,
									SQLiteCursorDriver masterQuery,
									String editTable, SQLiteQuery query) {
								return null;
							}
						});
				return db;
			} catch (Exception e) {
				return null;
			} finally {
				if (db != null)
					db.close();
			}
		}
    }
    class DeleteDbOnClickListener implements View.OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			try {
				if(DatabaseActivity.this.deleteDatabase(databaseNama)){
					vt_info.setText(getString(R.string.deleteDb_success));
				}else{
					vt_info.setText(getString(R.string.deleteDb_failure));
				}
				
			} catch (Exception e) {
				// TODO: handle exception
				vt_info.setText(e.getMessage());
			}
		}
    	
    }
    class CreateTableOnClickListener implements View.OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			SQLiteDatabase db = null;
			try {
				db = DatabaseActivity.this.openOrCreateDatabase(databaseNama, MODE_PRIVATE, null);
				if(db!=null){
					db.execSQL("create table "+tableNama+"(id integer primary key,name varchar2(100));");
					vt_info.setText(getString(R.string.createTable_success));
				}
				
			} catch (Exception e) {
				vt_info.setText(getString(R.string.createTable_failure)+"\n"+e.getMessage());
			}finally{
				if(db!=null) db.close();
			}
		}
    	
    }
    class DeleteTableOnClickListener implements View.OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			SQLiteDatabase db = null;
			try {
				db = DatabaseActivity.this.openOrCreateDatabase(databaseNama, MODE_PRIVATE, null);
				if(db!=null){
					db.execSQL("drop table "+tableNama+";");
					vt_info.setText(getString(R.string.deleteTable_success));
				}
				
			} catch (Exception e) {
				vt_info.setText(getString(R.string.deleteTable_failure)+"\n"+e.getMessage());
			}finally{
				if(db!=null) db.close();
			}
		}
    	
    }
    class InsertRecordOnClickListener implements View.OnClickListener{
    	
    	String id = null;
    	String name = null;
    	String sql = null;
    	SQLiteDatabase db = null;
    	Cursor cursor = null;

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			try {
				id = et_id.getText().toString();
				name = et_name.getText().toString();
				if(id==null||id.trim().length()==0){
					vt_info.setText("ID is null.");
					return ;
				}
				if(name==null||name.trim().length()==0){
					vt_info.setText("Name is null.");
					return ;
				}
				db = DatabaseActivity.this.openOrCreateDatabase(databaseNama, MODE_PRIVATE, null);
				sql = "select count(*) from "+tableNama+" where upper(id)='"+id.toUpperCase()+"'";
				cursor = db.rawQuery(sql, null);
				if(cursor.moveToFirst()){
					do{
						int num = cursor.getInt(0);
						if(num>0){
							vt_info.setText("The same record of id is exist.");
							return;
						}
					}while(cursor.moveToNext());
				}
				
				sql = "insert into "+tableNama+"(id,name) values('"+id+"','"+name+"')";
				db.execSQL(sql);
				
				vt_info.setText(getString(R.string.insert_success));
			} catch (Exception e) {
				// TODO: handle exception
				vt_info.setText(getString(R.string.insert_failure)+"\n"+e.getMessage());
			}finally{
				if(cursor!=null) cursor.close();
				if(db!=null) db.close();
			}
			
			
		}
    	
    }
    class UpdateRecordOnClickListener implements View.OnClickListener{

    	String id = null;
    	String name = null;
    	String sql = null;
    	SQLiteDatabase db = null;
    	Cursor cursor = null;

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			try {
				id = et_id.getText().toString();
				name = et_name.getText().toString();
				if(id==null||id.trim().length()==0){
					vt_info.setText("ID is null.");
					return ;
				}
				db = DatabaseActivity.this.openOrCreateDatabase(databaseNama, MODE_PRIVATE, null);
				sql = "update "+tableNama+" set name='"+name+"' where upper(id)=upper("+id+")";
				db.execSQL(sql);
				
				vt_info.setText(getString(R.string.update_success));
			} catch (Exception e) {
				// TODO: handle exception
				vt_info.setText(getString(R.string.update_failure)+"\n"+e.getMessage());
			}finally{
				if(cursor!=null) cursor.close();
				if(db!=null) db.close();
			}
			
			
		}
    	
    }
    class DeleteRecordOnClickListener implements View.OnClickListener{

    	String id = null;
    	String name = null;
    	String sql = null;
    	SQLiteDatabase db = null;
    	Cursor cursor = null;

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			try {
				id = et_id.getText().toString();
				name = et_name.getText().toString();
				if(id==null||id.trim().length()==0){
					vt_info.setText("ID is null.");
					return ;
				}
				db = DatabaseActivity.this.openOrCreateDatabase(databaseNama, MODE_PRIVATE, null);
				sql = "delete from "+tableNama+" where upper(id)=upper("+id+")";
				db.execSQL(sql);
				
				vt_info.setText(getString(R.string.delete_success));
				et_id.setText("");
				et_name.setText("");
			} catch (Exception e) {
				// TODO: handle exception
				vt_info.setText(getString(R.string.delete_failure)+"\n"+e.getMessage());
			}finally{
				if(cursor!=null) cursor.close();
				if(db!=null) db.close();
			}
			
			
		}
    	
    }
    class SelectRecordOnClickListener implements View.OnClickListener{

    	String id = null;
    	String name = null;
    	String sql = null;
    	SQLiteDatabase db = null;
    	Cursor cursor = null;
    	
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			try {
				db = DatabaseActivity.this.openOrCreateDatabase(databaseNama, MODE_PRIVATE, null);
				id = et_id.getText().toString();
				sql = "select id,name from " + tableNama + " where 1=1";
				if (id != null && id.trim().length() > 0)
					sql = sql + " and id=" + id + "";
				if (name != null && name.trim().length() > 0)
					sql = sql + " and upper(name) like %upper('" + name + "')%";
				cursor = db.rawQuery(sql, null);
				if (cursor.moveToFirst()) {
					et_id.setText(cursor.getString(0));
					et_name.setText(cursor.getString(1));
				}
				vt_info.setText(getString(R.string.select_success));
					
			} catch (Exception e) {
				// TODO: handle exception
				vt_info.setText(getString(R.string.select_failure)+"\n"+e.getMessage());
			}finally{
				if(cursor!=null) cursor.close();
				if(db!=null) db.close();
			}
			
			
		}
    	
    }
}


Android数据库编程SQLite详解_第1张图片

你可能感兴趣的:(Android数据库编程SQLite详解)