Android中sqlite基本使用1,(创建数据库,升级,对数据进行增、删、改、查)

来源:互联网 发布:58动漫网站源码 编辑:程序博客网 时间:2024/05/02 07:42

前面我们用文件存储和SharedPreference存储毕竟只适用去保存一些简单数据

和键值对,当需要存储大量复杂的关系型数据的时候,比如手机短信中可能存

在很多条会话,每个会话又包含了很多条信息内容,并且大部分会话还可能对应

电话簿中的某个联系人,这时候就要使用SQLite数据库了。


SQLiteOpenHelper 类可以创建数据库和表,和升级。

SQLiteDatabase类 可以对数据库进行增删改查操作。

创建的数据库存储在/data/data/<package name>/database/目录下




我写了一个简单例子

项目结构如下


核心代码:

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >


    <Button
        android:id="@+id/create_btn_database"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="创建数据库" />


    <Button
        android:id="@+id/btn_adddata"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="添加数据" />
     <Button
        android:id="@+id/btn_updatedata"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="更新数据" />
     <Button
        android:id="@+id/btn_deletedata"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="删除数据" />
     <Button
        android:id="@+id/btn_query_data"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="查询数据" />
   
</LinearLayout>

MyDatabaseHelper中

/**
 *SQLiteOpenHelper是用来创建数据库和表的
 *
 */


public class MyDatabaseHelper extends SQLiteOpenHelper {
/*
*autoincrement表示id列是自增长的
*integer表示整型
*real表示浮点
*text表示文本类型
*blob表示二进制类型

* */
public static final String CREATE_BOOK="create table Book(" +
                               "id integer primary key autoincrement," +
                               "author text," +
                               "price real," +
                               "pages integer," +
                               "name text)";
public static final String CREATE_CATEGORY="create table Category(" +
                               "id integer primary key autoincrement," +
                               "category_name text" +
                               "category_code integer)";
private Context mContext;


public MyDatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
mContext=context;
}
    /**
     *这个方法在创建数据库的时候,系统只调用一次
     */
@Override
public void onCreate(SQLiteDatabase db) {
//数据库创建完成,同时创建book表
db.execSQL(CREATE_BOOK);
db.execSQL(CREATE_CATEGORY);
Toast.makeText(mContext, "创建成功", Toast.LENGTH_LONG).show();

}



/**
* 要想执行这个方法只要在new MyDatabaseHelper(this, "BookStore.db", null, 1);
* 传入的版本号大于之前传的,系统就可以调用此方法
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists Book");
db.execSQL("drop table if exists Category");
onCreate(db);
/*如果数据库中已经存在Book,Category的表了,就将这两张表删掉,然后调用onCreate();方法
* 重新创建,这里现将存在的表删掉,是因为如果在创建表示发现这张表已经存在了,就会直接报错
* */
}


}//class

MainActivity中

/**
 * SQLiteDatabase,对数据进行增删改查。
 *
 */
public class MainActivity extends Activity {


private MyDatabaseHelper dbHelper;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**
* 创建数据库
*/
// 指定数据库的名称BookStore.db,版本号是1
dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 2);
Button createDatabase_btn = (Button) findViewById(R.id.create_btn_database);
createDatabase_btn.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
// 得到一个能写的数据库
dbHelper.getWritableDatabase();


}
});
/**
* 添加数据
*/
Button addData_btn = (Button) findViewById(R.id.btn_adddata);
addData_btn.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
/* SQLiteDatabase类才能对数据库操作,即增删改查 */
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
// 开始组装第一条数据
values.put("name", "The Da Vinci code");
values.put("author", "Dan Brown");
values.put("pages", 454);
values.put("price", 16.96);
db.insert("Book", null, values);// 插入第一条数据
values.clear();
// 开始组装第二条数据
values.put("name", "The Lost Symbol");
values.put("author", "Dan Brown");
values.put("pages", 510);
values.put("price", 19.95);
db.insert("Book", null, values);// 插入第二条数据
Toast.makeText(MainActivity.this, "数据已添加", 10).show();

// /**除了可以用android分装的方法进行增删该查,还可以直接用sql语句
// * 下面是用方法实现相同功能,增删改都调用execSQL两个参数的方法,查询调用rawQuery方法*/
// //增加
// db.execSQL("insert into Book(name,author,pages,price)values(?,?,?,?)",new String[]{"The Da Vinci Code","Dan Brown","454","16.96"});
// db.execSQL("insert into Book(name,author,pages,price)values(?,?,?,?)",new String[]{"The Lost Symbol","Dan brown","510","19.95"});
// //删除
// db.execSQL("delete from Book where pages >?", new String[]{"500"});
// //更新
// db.execSQL("update Book set price=?where name=?", new String[]{"10.99","The Da Vinci Code"});
// //查询
// db.rawQuery("select*from Book", null);

}
});
/**
* 更新数据
*/
Button updatedata_btn = (Button) findViewById(R.id.btn_updatedata);
updatedata_btn.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("price", 10.99);
db.update("Book", values, "name=?",
new String[] { "The Da Vinci code" });
/* 上述代码的意思是:将名字是The Da Vinci Code 这本书的价格改成10.99 */
Toast.makeText(MainActivity.this, "修改成功", 10).show();
}
});
/**
* 删除数据
*/
Button deletedata_btn = (Button) findViewById(R.id.btn_deletedata);
deletedata_btn.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.delete("Book", "pages>?", new String[] { "500" });
/* 删除页数超过500的书籍 */
Toast.makeText(MainActivity.this, "删除成功", 10).show();
}
});
/**
* 查询数据
*/
Button querydata_btn = (Button) findViewById(R.id.btn_query_data);
querydata_btn.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("Book", null, null, null, null, null,
null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor
.getColumnIndex("name"));
String author = cursor.getString(cursor
.getColumnIndex("author"));
int pages = cursor.getInt(cursor
.getColumnIndex("pages"));
double price = cursor.getDouble(cursor
.getColumnIndex("price"));
Log.d("1", "name。。。" + name);
Log.d("1", "author。。。" + author);
Log.d("1", "pages。。。" + pages);
Log.d("1", "price。。。" + price);


} while (cursor.moveToNext());
cursor.close();


}
Toast.makeText(MainActivity.this, "查询成功", 10).show();


}
});


}// onCreate



}// class

如果没有看懂请下载我的例子和测试方法

http://download.csdn.net/detail/zhaihaohao1/8325271



0 0
原创粉丝点击