Android中有关数据库SQLite的介绍

SQLite是android提供的一个关系型数据库。今天要总结的主要内容就是它。

在使用SQLite的时候用到的抽象类是

SQLiteOpenHelper

有关这个函数的详细内容你可以在Android的官方文档中找到:http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html
public SQLiteDatabase getReadableDatabase ()
Added in  API level 1

Create and/or open a database. This will be the same object returned by getWritableDatabase() unless some problem, such as a full disk, requires the database to be opened read-only. In that case, a read-only database object will be returned. If the problem is fixed, a future call togetWritableDatabase() may succeed, in which case the read-only database object will be closed and the read/write object will be returned in the future.

Like getWritableDatabase(), this method may take a long time to return, so you should not call it from the application main thread, including fromContentProvider.onCreate().

Returns
Throws
SQLiteException if the database cannot be opened
他是用于创建或者打开一个数据库
要使用SQLiteOpenHelper这个类我们必须自己新建一个类来继承他才能使用
下面记录详细的学习过程:
首先打开Eclipse之后新建一个android的项目文件之后新建一个包,名字任意取,只要符合android的命名规则即可
之后在里面新建一个类叫DatabaseHelper让他继承刚才我们提到过的SQLiteOpenHelper这个类,复写其中的抽象方法
package sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper{

	public DatabaseHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		
	}

}
注意在其中必须添加一个构造函数DatabaseHelper,其中有四个参数Context指的就是他的Activity参数,第二个参数指的是表的名字,第三个参数一般传的是空值,最后一个指的是当前的数据库的版本。数据库的版本是正数而且必须是递增的。
之后我们在构造两个构造函数
private static final int VERSION = 1;
	public DatabaseHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
		// TODO Auto-generated constructor stub
	}
	
	public DatabaseHelper(Context context,String name,int version){
		this(context,name,null,version);
	}

	public DatabaseHelper(Context context,String name){
		this(context,name,VERSION);
	}
	
其中第二个构造函数是调用第一个构造函数,他自身含有三个参数
第三个构造函数是调用第二个构造函数,他自身含有两个参数
其中在第三个构造函数中我们可以看出来第三个实参用的是我们自己定义的一个整型常量他的默认值是1;

之后我们来关注OnCreate()函数
@Override
	public void onCreate(SQLiteDatabase arg0) {
		// TODO Auto-generated method stub
		System.out.println("create a Database");
		arg0.execSQL("create table user(id int , name varchar(20))");
	}
我们在其中添加一句打印输出的语句和一个execSQL函数,它是用于执行SQL语句
在这里我们通过OnCreate这个函数来建立一张表,它的名字我们取名为user,它包含了两项,其中之一是用户的id,另一项是用户的名字我们让他占用20个字节
之后我们在XML文件中编写好Activity的布局文件
之后可以得到如下图所示的界面:

这个界面的代码对应如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello_world"
    />
<Button
	android:id="@+id/createDatabase"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="createDatabase"
    />
    
<Button
	android:id="@+id/updateDatabase"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="updateDatabase"
    />

<Button
	android:id="@+id/insert"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="insert"/>
<Button
	android:id="@+id/update"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="update"/>
<Button
	android:id="@+id/query"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="query"/>
	
</LinearLayout>

这个时候点击createDatabase用于更新数据库,点击updateDatebase用于更新数据库,顾名思义:insert,query,update分别对应于插入,查询,更新操作。

下面我们来详细分析一下他们是如何实现的:
基本思路自然是现在MainActivity里面设置如上所示的几个按钮,之后为他们绑定好监听器即可:
使用findViewById()实现
createButton = (Button)findViewById(R.id.createDatabase);
        updateButton = (Button)findViewById(R.id.updateDatabase);
        insertButton = (Button)findViewById(R.id.insert);
        updateRecordButton = (Button)findViewById(R.id.update);
        queryButton = (Button)findViewById(R.id.query);
	
        createButton.setOnClickListener(new CreateListener());
        updateButton.setOnClickListener(new UpdateListener());
        insertButton.setOnClickListener(new InsertListener());
        updateRecordButton.setOnClickListener(new UpdateRecordListener());
        queryButton.setOnClickListener(new QueryListener());

为每一个按钮实现一个监听器:
class CreateListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			DatabaseHelper dbHelper =new DatabaseHelper(MainActivity.this,"test_db");
			SQLiteDatabase db =dbHelper.getReadableDatabase();
		}
		
	}
上面实现的是建立一个数据库的功能,这里我们引入了刚才建立的DatabaseHelper这一个类,其中MainActivity是该类的名字,数据库的名字我们叫做test_db;这里我们调用刚才DatabaseHelper两个参数的构造函数
之后使用SQLiteDatabase 读取数据库

实现更新数据库的操作:
class UpdateListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			DatabaseHelper dbHelper =new DatabaseHelper(MainActivity.this,"test_db",2);
			SQLiteDatabase db =dbHelper.getReadableDatabase();
		}
		
	}
和上面的那个操作差不多,唯一不同的是调用的构造函数不同
class InsertListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			ContentValues values =new ContentValues();
			values.put("id", 1);
			values.put("name", "LiHua");
			DatabaseHelper dbHelper= new DatabaseHelper(MainActivity.this,"test_db",2);
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			db.insert("user", null, values);
			
		}	
    }
这里我们使用到了ContentValues函数,这个在数据库当中是很常用的函数他用来对数据库的成员进行赋值(或许说的不准确)是键值对,前面是关键字,后面对应的是输入的值
由于插入是要写所以对应的是getWritableDatabase()这个函数
使用了insert函数,其第一个参数名“user”对应的是表格名字,第三个对应的是设置的键值对

更新数据库中的值

class UpdateRecordListener implements OnClickListener{


		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			ContentValues values =new ContentValues();
			values.put("name", "zhangsan");
			DatabaseHelper dbHelper= new DatabaseHelper(MainActivity.this,"test_db",2);
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			db.update("user", values, "id=?", new String[]{"1"});
			
		}
    	
    }
思路仍然是一样的:
使用ContentValues 
注意这里的更新是真的某个特定的值来更新,不是对数据库进行更新,就比如说这里就是对数据库的对应id=1的数据的用户名进行更改
id="?"是占位符,他有几个之后的string数组也要有几个
class QueryListener implements OnClickListener{


		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			DatabaseHelper dbHelper = new DatabaseHelper(MainActivity.this,"test_db");
			SQLiteDatabase db = dbHelper.getReadableDatabase();
                        //相当于查询语句  user是表格的名字
			Cursor cursor = db.query("user", new String[]{"id","name"}, "id=?", new String[]{"1"}, null, null, null);
			while(cursor.moveToNext()){
				String name = cursor.getString(cursor.getColumnIndex("name"));
				System.out.println("query--->" + name);
			}
		}
    	
    }




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值