zoukankan      html  css  js  c++  java
  • Android——SQLite实现面向对象CRUD

           android中SQLite的使用,事实上倒也不难。可是与JDBC操作数据库相比,这个还是有点不顺手,并且我好久没写底层的封装了,使用SSM框架这些都不须要考虑......好了,废话不多说。以下直接建立一个測试project来试试SQLite在Android中的应用吧。


    1、新建一个project




    2、配置junit測试环境

    打开AndroidManifest.xml文件,进行jUnit相关配置,详细例如以下图:



    3、源代码

            关于在Android中怎样使用SQLite的文章非常多,我也是參考那些文章进行学习的。

    作为一个J2EE方向的开发人员,我习惯于面向对象进行编程,而老罗的视频以及一些其它的教程关于CRUD操作使用的都是字符串,这我有点不适应,全部我在学习的过程中就改成了面向对象的CRUD操作。这样用着也方便点。原理、API什么的我就不说了。百度一下嗖嗖的都出来了,以下直接贴代码(完整project下载。点这里):

          这样一个继承SQLiteOpenHelper的类主要就这么几个功能:

               a.创建数据库和表

               b.假设数据库有不同版本号那么就会更新数据库

               c.调用的这个类的对象来取得数据库的读写权限


    package com.example.db;
    
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    public class DBHelper extends SQLiteOpenHelper {
    
    	private static final String DATABASE_NAME = "test.db";
    	private static final int DATABASE_VERSION = 1;
    
    	public DBHelper(Context context) {
    		// CursorFactory设置为null,使用默认值
    		super(context, DATABASE_NAME, null, DATABASE_VERSION);
    	}
    
    	// 数据库第一次被创建时onCreate会被调用
    	@Override
    	public void onCreate(SQLiteDatabase db) {
    		String sql = "CREATE TABLE IF NOT EXISTS person "
    				+ "(id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(32),sex VARCHAR(8))";
    		db.execSQL(sql);
    	}
    
    	// 假设DATABASE_VERSION值被改为2,系统发现现有数据库版本号不同,即会调用onUpgrade
    	@Override
    	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    		db.execSQL("ALTER TABLE base_info ADD COLUMN other STRING");
    	}
    }
    

    能够看到上面创建了一个叫test.db的数据库。当中有一个表person,表中有三个字段:主键-id。姓名-name,性别-sex。


    以下生成这个表相应的实体类:

    package com.example.pojo;
    
    public class Person {
    	private int id;
    	private String name;
    	private String sex;
    	public int getId() {
    		return id;
    	}
    	public void setId(int id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getSex() {
    		return sex;
    	}
    	public void setSex(String sex) {
    		this.sex = sex;
    	}
    	@Override
    	public String toString() {
    		return "Person [id=" + id + ", name=" + name + ", sex=" + sex + "]";
    	}
    	
    }
    

    我们要实现CRUD操作,那么建一个接口定义CRUD方法:

    package com.example.dao;
    
    import com.example.pojo.Person;
    
    public interface IPersonDao {
    	public boolean insert(Person person);
    	public boolean delete(int id);
    	public boolean update(Person person);
    	public Person select(int id);
    }
    

    以下要实现IPersonDao接口。定义详细的业务方法:

    package com.example.dao.impl;
    
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    
    import com.example.dao.IPersonDao;
    import com.example.db.DBHelper;
    import com.example.pojo.Person;
    
    public class PersonDaoImpl implements IPersonDao {
    	DBHelper helper = null;
    	
    	public PersonDaoImpl(Context context){
    		helper = new DBHelper(context);
    	}
    
    	@Override
    	public boolean insert(Person person) {
    		boolean flag = false;
    		SQLiteDatabase database = null;
    		try {
    			String sql = "INSERT INTO person(name,sex) VALUES (?,?)";
    			database = helper.getWritableDatabase();
    			database.execSQL(sql, new Object[]{person.getName(),person.getSex()});
    			flag = true;
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			if(database!=null){
    				database.close();
    			}
    		}
    		return flag;
    	}
    
    	@Override
    	public boolean delete(int id) {
    		boolean flag = false;
    		SQLiteDatabase database = null;
    		try {
    			String sql = "DELETE FROM person WHERE id=?";
    			database = helper.getWritableDatabase();
    			database.execSQL(sql, new Object[]{Integer.toString(id)});
    			flag = true;
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			if(database!=null){
    				database.close();
    			}
    		}
    		return flag;
    	}
    
    	@Override
    	public boolean update(Person person) {
    		boolean flag = false;
    		SQLiteDatabase database = null;
    		try {
    			String sql = "UPDATE person set name=? , sex=? where id=?";
    			database = helper.getWritableDatabase();
    			database.execSQL(sql, new Object[]{person.getName(),person.getSex(),person.getId()});
    			flag = true;
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			if(database!=null){
    				database.close();
    			}
    		}
    		return flag;
    	}
    
    	@Override
    	public Person select(int id) {
    		Person person = new Person();
    		SQLiteDatabase database = null;
    		try {
    			String sql = "SELECT * FROM person where id=?";
    			database = helper.getReadableDatabase();			
    			Cursor cursor = database.rawQuery(sql, new String[]{Integer.toString(id)});
    			while(cursor.moveToNext()){
    				int _id = cursor.getInt(cursor.getColumnIndex("id"));
    				String _name = cursor.getString(cursor.getColumnIndex("name"));
    				String _sex = cursor.getString(cursor.getColumnIndex("sex"));
    				person.setId(_id);
    				person.setName(_name);
    				person.setSex(_sex);
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}finally{
    			if(database!=null){
    				database.close();
    			}
    		}
    		return person;
    	}
    	
    	
    
    }
    

    以上完毕之后就能够開始单元測试了。绿色......

    package com.example.test;
    
    import com.example.dao.IPersonDao;
    import com.example.dao.impl.PersonDaoImpl;
    import com.example.pojo.Person;
    
    import android.test.AndroidTestCase;
    import android.util.Log;
    
    public class Test extends AndroidTestCase {
    	public void insertDB(){
    		IPersonDao personDao = new PersonDaoImpl(getContext());
    		Person person = new Person();
    		person.setName("李四");
    		person.setSex("男");
    		personDao.insert(person);
    	}
    	
    	public void selectDB(){
    		IPersonDao personDao = new PersonDaoImpl(getContext());
    		Person person = personDao.select(1);
    		Log.i("info", person.toString());
    	}
    	
    	public void updateDB(){
    		IPersonDao personDao = new PersonDaoImpl(getContext());
    		Person person = personDao.select(1);
    		person.setName("改名字啦");
    		person.setSex("不详");
    		personDao.update(person);
    	}
    	
    	public void deleteDB(){
    		IPersonDao personDao = new PersonDaoImpl(getContext());
    		personDao.delete(2);
    	}
    
    }
    


    导出test.db文件。在SQLite Expert中打开:



    这是insert測试成功的样例。其它就不放图了,这个软件百度就能够下载了。



    (转载注明出处:http://blog.csdn.net/zhshulin)

  • 相关阅读:
    八、比卦
    七、师卦
    六、讼卦
    五、需卦
    力扣-两数之和
    什么是3NF (范式) ?
    SQL事务4个特性
    什么是索引?
    假设把只包含01的数组(如{0,0,1,1,1,0,1,0,0,1})按照升序排序,可以任意交换两个数的位置,请输出最少需要交换的次数。
    找规律并用编程实现如下数列(数值超过10000停止打印) 1,1,2,2,3,2,5,4,8,8
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/5239952.html
Copyright © 2011-2022 走看看