android开发笔记-sqllite数据库的操作

1.SQLLite简介:

        在Android平台上,集成了一个嵌入式关系型数据库—SQLite,SQLite3支持 NULL、INTEGER、REAL(浮点数字)、TEXT(字符串文本)和BLOB(二进制对象)数据类型,虽然它支持的类型虽然只有五种,但实际上 sqlite3也接受varchar(n)、char(n)、decimal(p,s) 等数据类型

 

2. 使用详解:

SQLiteOpenHelper:  对SQLLite数据库操作的辅助工具类.

 

变量:

public static final String KEY_ID = "stock_id";// 数据库id
	public static final String CODE = "stock_code";// 各类类型id
	public static final String NAME = "stock_name";
	public static final String SIMPLE = "stock_simple";
	private String TAG = "StockDBAdapter" ;
	  
	private static final String DATABASE_CREATE = " create table if not exists "
			+ DATABASE_TABLE
			+ " ("
			+ KEY_ID
			+ " integer primary key autoincrement,"
			+ CODE
			+ " varchar, "
			+ NAME
			+ " varchar, "
			+ SIMPLE
			+ " varchar); ";
 

一、创建和打开数据库:

public StockDBAdapter(Context ct) {
		this.context = ct;
		dbHelper = new DBHelper(context, DATABASE_NAME, null, DATABASE_VERSION,
				DATABASE_NAME, DATABASE_CREATE);
	}

   二、打开数据库:

	public List<Map<String , String>> selectStock(String key){
		
		if(!db.isOpen()){
			db = dbHelper.getReadableDatabase();
		}
		
		List<Map<String , String>> stockList = new ArrayList<Map<String , String>>();
		
		Cursor cur = null;
		
		if(null!=key && !"".equals(key)){

			//查询的列字段名
			String [] columns = {CODE , NAME , SIMPLE};
			//查询条件
			String where =  CODE+ " like ? or "+NAME+" like ? or "+SIMPLE+" like ? ";
			//查询参数
			String [] selectArgs = {key+"%" , key+"%" , key+"%"}; 
			//执行查询
			cur = db.query(DATABASE_TABLE, columns, where , selectArgs, null, null, null);
			
			cur.moveToFirst();
			//循环读取数据
			while(!cur.isAfterLast()){
				Map<String , String> stockMap = new HashMap<String , String>();
				String code =  cur.getString(0);
				String name =  cur.getString(1)+"("+code+")";
				stockMap.put("code" , code);
				stockMap.put("name" , name);
				stockList.add(stockMap);
				cur.moveToNext();
			}
			cur.close();
			close();
			return stockList;
		}
		return null;
	}
  

你可能感兴趣的:(Android开发)