Android-数据库Sqlite的创建,查询及在ListView显示

之前一直没用到数据库,也就没看。突然有一天要用到才想去看,无奈得不到精髓,在这一块也是消沉了好几天都没有进展,而且也看了蛮多的博客,看完之后居然像没看过一样,好囧尴尬再见。。。。我也不知道是不是新手都这样,如果是,那我一定很理解,如果不是,那只能说我自己太懒了,没有动手的能力。

后来看了Mars老师的视频,然后跟着敲代码,代码跟着一样,运行却一直出现异常,百度上说异常的出现可能是Sql语句有错误,存在空格也不行,检查无果,只能复制粘贴源代码了,正常运行。

所以就在Mars老师的代码基础上来记录一下Sqlite的简单使用,并实现了查询数据库并在ListView上显示。

布局管理器里面加入几个Button和一个ListView:

<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"
    tools:context=".MainActivity" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/create"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:text="createDatabase" />

        <Button
            android:id="@+id/updateDatabase"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/delete"
            android:layout_alignLeft="@+id/query"
            android:text="updateDatabase" />

        <Button
            android:id="@+id/insert"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/create"
            android:text="insert" />

        <Button
            android:id="@+id/update"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/insert"
            android:layout_alignBottom="@+id/insert"
            android:layout_toLeftOf="@+id/updateDatabase"
            android:text="update" />

        <Button
            android:id="@+id/query"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/update"
            android:layout_alignBottom="@+id/update"
            android:layout_toRightOf="@+id/create"
            android:text="query" />

        <Button
            android:id="@+id/delete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/query"
            android:layout_alignBottom="@+id/query"
            android:layout_toRightOf="@+id/query"
            android:text="delete" />
    </RelativeLayout>

    <ListView
        android:id="@android:id/list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout>
为ListView的样式布局list.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="horizontal" >
	<TextView
        android:id="@+id/_id"
        android:layout_width="80px"
        android:layout_height="40sp"
        android:text="id" />
    <TextView
        android:id="@+id/name"
        android:layout_width="250px"
        android:layout_height="40sp"

        android:text="name" />

    <TextView
        android:id="@+id/credit"
        android:layout_width="80px"
        android:layout_height="40sp"
        android:text="credit" />

</LinearLayout>
接下来就是重点了,对于数据库, Android平台提供给我们一个辅助类帮助创建和管理数据库——SQLiteOpenHelper,其使用方法如下:

SQLiteOpenHelper是一个辅助类来管理数据库的创建和版本。 
可以通过继承这个类,实现它的一些方法来对数据库进行一些操作。 
所有继承了这个类的类都必须实现下面这样的一个构造方法: 
public DatabaseHelper(Context context, String name, CursorFactory factory, int version) 
 1、Context类型,上下文对象。 
2、String类型,数据库的名称 
3、CursorFactory类型 
4、int类型,数据库版本 
所以,第一步,需要新建一个类继承SQLiteOpenHelper,名字为DatabaseHelper.java

package com.sqlite.db;

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{
	private static final int VERSION = 1;
	private String TABLE_NAME = "kecheng";
	
	//四个参数的构造方法
	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);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		System.out.println("create a Database");
		StringBuffer sBuffer = new StringBuffer();
        sBuffer.append("CREATE TABLE [" + TABLE_NAME  + "] (");    //创建表和定义表明
        sBuffer.append("[_id] INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, ");//设置_id为主键,不能为空与自增性质
        sBuffer.append("[name] TEXT,");   //一个为name的列名,类型为text,这点不同于java中的String
        sBuffer.append("[credit] INTEGER)");  //一个为credit的列名,类型为INTEGER整型,代表学分
        db.execSQL(sBuffer.toString());
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		System.out.println("upgrade a Database");
	}
	

}
之后就是在mainActivity.java中调用创建数据库,注释写得很清楚,就不多啰嗦了。

package com.Android.sqlite;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.sqlite.db.DatabaseHelper;
import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {
	//定义Button,ListView,list数据集合,simpleAdapter适配器
	private Button create, updateDatabase, insert, updatebtn, query, delete;
	private ListView listview = null;
	private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
	private SimpleAdapter simpleAdapter = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//取得组件
		create = (Button) findViewById(R.id.create);
		updateDatabase = (Button) findViewById(R.id.updateDatabase);
		insert = (Button) findViewById(R.id.insert);
		updatebtn = (Button) findViewById(R.id.update);
		query = (Button) findViewById(R.id.query);
		delete = (Button) findViewById(R.id.delete);
		listview = (ListView) findViewById(android.R.id.list);
		//绑定事件监听器
		create.setOnClickListener(new CreateListener());
		updateDatabase.setOnClickListener(new UpdateDatabaseListener());
		insert.setOnClickListener(new InsertListener());
		updatebtn.setOnClickListener(new UpdateListener());
		query.setOnClickListener(new QueryListener());
		delete.setOnClickListener(new DeleteListener());
		
		//适配器添加查询结果,并加到ListView中显示
		simpleAdapter = new SimpleAdapter(this, getData(), R.layout.list,
				new String[] { "_id", "name", "credit" }, new int[] {
						R.id._id, R.id.name, R.id.credit });
		listview.setAdapter(simpleAdapter);
		
	}

	class CreateListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			// 创建一个DatabaseHelper对象
			DatabaseHelper dbHelper = new DatabaseHelper(MainActivity.this,
					"test_my_db");
			// 只有调用了DatabaseHelper对象的getReadableDatabase()方法,或者是getWritableDatabase()方法之后,才会创建,或打开一个数据库
			SQLiteDatabase db = dbHelper.getReadableDatabase();
		}
	}

	class UpdateDatabaseListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			DatabaseHelper dbHelper = new DatabaseHelper(MainActivity.this,
					"test_my_db", 2);
			SQLiteDatabase db = dbHelper.getReadableDatabase();
		}
	}

	class InsertListener implements OnClickListener {

		@Override
		public void onClick(View v) {
		
			DatabaseHelper dbHelper = new DatabaseHelper(MainActivity.this,
					"test_my_db", 2);
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			//插入数据语句,以事务处理方式插入
			//主键不需要插入,会自己出现并自增
			db.beginTransaction(); //开始事务处理
			db.execSQL("insert into kecheng(name,credit) values('java基础',2)");
			db.execSQL("insert into kecheng(name,credit) values('移动通信',3)");
			db.execSQL("insert into kecheng(name,credit) values('通信原理',2)");
			db.execSQL("insert into kecheng(name,credit) values('单片机设计',1)");
			db.execSQL("insert into kecheng(name,credit) values('光纤通信',3)");
			db.execSQL("insert into kecheng(name,credit) values('电磁场与电磁波',2)");
			db.execSQL("insert into kecheng(name,credit) values('微波通信系统',3)");
			db.execSQL("insert into kecheng(name,credit) values('大学英语',2)");
			db.execSQL("insert into kecheng(name,credit) values('模拟电子线路',3)");
			db.execSQL("insert into kecheng(name,credit) values('数字电子线路',2)");
			db.execSQL("insert into kecheng(name,credit) values('高等数学',3)");
			db.execSQL("insert into kecheng(name,credit) values('C语言',3)");
			db.execSQL("insert into kecheng(name,credit) values('EDA设计',2)");
			db.execSQL("insert into kecheng(name,credit) values('传感器原理应用',3)");
			db.setTransactionSuccessful();  //设置事务标志为成功,当结束事务时就会提交事务
			db.endTransaction();//结束事务
		}
	}

	// 更新操作就相当于执行SQL语句当中的update语句
	// UPDATE table_name SET XXCOL=XXX WHERE XXCOL=XX...
	class UpdateListener implements OnClickListener {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			// 得到一个可写的SQLiteDatabase对象
			DatabaseHelper dbHelper = new DatabaseHelper(MainActivity.this,
					"test_my_db");
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			//更新_id=5的数据,语句很容易理解
			db.execSQL("UPDATE kecheng SET name='通信原理1111',credit=4 WHERE _id=5");
		}
	}

	class QueryListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			System.out.println("aaa------------------");
			DatabaseHelper dbHelper = new DatabaseHelper(MainActivity.this,
					"test_my_db");
			SQLiteDatabase db = dbHelper.getReadableDatabase();
			//下面是查询语句
			Cursor cursor = db.rawQuery("select * from kecheng ",
					null);
			while (cursor.moveToNext()) {    //获取游标下移,作为循环,从而获得所有数据
				String id = cursor.getString(0);  //获取_id
				String name = cursor.getString(1); //获取name
				String credit = cursor.getString(2);//获取credit学分		
				System.out.println("query--->" + id + "," + name + "," + credit);//输出数据
			}
		}}
	class DeleteListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			DatabaseHelper dbHelper = new DatabaseHelper(MainActivity.this,
					"test_my_db");
			SQLiteDatabase db = dbHelper.getReadableDatabase();
			db.execSQL("delete from kecheng where credit=2");//删除 学分为2的数据
		}
		 
	}
	private List<Map<String, Object>> getData() {
		DatabaseHelper dbHelper = new DatabaseHelper(MainActivity.this,
				"test_my_db");
		SQLiteDatabase db = dbHelper.getReadableDatabase();
		Cursor cursor = db.rawQuery("select * from kecheng where credit=3",
				null);
		while (cursor.moveToNext()) {
			String id = cursor.getString(0);
			String name = cursor.getString(1);
			String credit = cursor.getString(2);
			//这里同样是查询,只不过把查询到的数据添加到list集合,可以参照ListView的用法
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("_id", id); //获取_id
			map.put("name", name);	//获取name
			map.put("credit", credit); //获取credit学分
			list.add(map);
				//System.out.println("query--->" + id + "," + name + "," + credit);
			}
		return list;
		
	}
	
}

第一次运行,界面如第一个图,可能会有人注意到,ListView没有数据显示啊?原因很简单,因为我们把创建数据库的操作和createDatabese按钮绑定了,此时,当我们按下createDatabase按钮时,数据库才被创建,之后点击insert按钮,导入数据,我们可以使用adb调试工具来看看是否成功,如第二个图,很明显,数据已成功插入,关于adb的使用在这里就不讲了,有需要的童鞋可以自己百度或者call me.



当点击query按钮的时候,可以看到在LogCat下面已有数据输出,这里我们的查询条件是输出表内的所有数据,故查询语句里面使用*来代替。当重启启动程序,此时由于数据库以创建,故ListView显示出了数据。


还有关于删除,更新数据库等,就不一一贴图了,代码都是可以正常运行的,可能对于大神来说,这些小操作根本就不值得一提,不过对于想自己这样的新手来说,我觉得分享出来还是很值得的。




评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值