数据存储之SQLite

dbHelper.java

package com.terry;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

public class dbHelper extends SQLiteOpenHelper {

	private final static String DATABASE_NAME="sec_db";
	private final static int DATABASE_VERSION=1;
	private final static String TABLE_NAME="sec_pwd";
	public final static String FIELD_ID="_id"; 
	public final static String FIELD_TITLE="sec_Title";
	
	
	public dbHelper(Context context)
	{   
		/**
		 * 通过构造函数来创建数据库,如果进入此函数,不存在此数据库则创建,如果存在此数据库则打开连接,
		 * 只要进入此方法就可以用打开的连接获得getWritableDatabase()或getReadableDatabase()这两个方法。
		 */
		super(context, DATABASE_NAME,null, DATABASE_VERSION);
		
	}
	
	
	 /**
	  * 一个数据库中可以包含多个表,每一条数据都存在指定的表中,要创建可以通过 execSQL 方法来执行一条 SQL 语句。
	  */
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		//创建了表名为“sec_pwd” 的数据表,表内存在一个 integer 类型的主键和一个 text 类型的字段,并执行创建该表。
		String sql="Create table "+TABLE_NAME+"("+FIELD_ID+" integer primary key autoincrement,"
		+FIELD_TITLE+" text );";
		db.execSQL(sql);
		
		 
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		String sql=" DROP TABLE IF EXISTS "+TABLE_NAME;
		db.execSQL(sql);
		onCreate(db);
	}
    
	/**
	 * 查询数据
	 * @return
	 */
	public Cursor select()
	{
		SQLiteDatabase db=this.getReadableDatabase();
		Cursor cursor=db.query(TABLE_NAME, null, null, null, null, null,  " _id desc");
	   
		return cursor;
	}
	/**
	 * 添加数据
	 * @param Title
	 * @return
	 */
	public long insert(String Title)
	{   
		/**
		 * 封装了一个使用SQLite 的 insert 方法,向表中添加数据,但是insert 方法要求把数据都打包到 ContentValues 中,
		 *  ContentValue 其实可就是一个 HashTable,Key值是字段名称,Value 值是字段的值。
		 * 通过 ContentValues 的put 方法就可以把数据库放到 ContentValue 对象中,然后插入到表中去。
		 */
		SQLiteDatabase db=this.getWritableDatabase();
		ContentValues cv=new ContentValues(); 
		cv.put(FIELD_TITLE, Title);
		long row=db.insert(TABLE_NAME, null, cv);
		return row;
	}
	/**
	 * 删除数据
	 * @param id
	 */
	public void delete(int id)
	{
		SQLiteDatabase db=this.getWritableDatabase();
		String where=FIELD_ID+"=?";
		String[] whereValue={Integer.toString(id)};
		db.delete(TABLE_NAME, where, whereValue);
	}
	
	/**
	 * 修改数据
	 * @param id
	 * @param Title
	 */
	public void update(int id,String Title)
	{
		SQLiteDatabase db=this.getWritableDatabase();
		String where=FIELD_ID+"=?";
		String[] whereValue={Integer.toString(id)};
		ContentValues cv=new ContentValues(); 
		cv.put(FIELD_TITLE, Title);
		db.update(TABLE_NAME, cv, where, whereValue);
	}
	
	
	
	
}

  这里用到了Menu做功能按钮,实例代码如下:

 package com.terry;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursor;
import android.os.Bundle; 
import android.view.Menu;  
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;


public class testDbActivity extends Activity {
	
	private dbHelper db;
	private Cursor myCursor;
	private ListView myListView;
	private EditText myEditText;
	private int _id;
	protected final static int MENU_ADD=Menu.FIRST;
	protected final static int MENU_EDIT=Menu.FIRST+1;
	protected final static int MENU_DELETE=Menu.FIRST+2;
	
	   @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		   super.onCreateOptionsMenu(menu);
		menu.add(Menu.NONE, MENU_ADD, 0, R.string.ADD);
		menu.add(Menu.NONE, MENU_EDIT, 0,R.string.EDIT);
		menu.add(Menu.NONE, MENU_DELETE, 0,R.string.DELETE);
		 return true;
	}
	
	   @Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		
		super.onOptionsItemSelected(item); 
		switch (item.getItemId()) {
		case MENU_ADD:
			operation("add");
			break;
		case MENU_EDIT:
			operation("edit");
			break;
		case MENU_DELETE:
			operation("delete");
			break;
		default:
			break;
		}
		return true;
	}
	   
	   
	   
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myEditText=(EditText)findViewById(R.id.EditText1);
        myListView=(ListView)findViewById(R.id.ListView1);
        db=new dbHelper(testDbActivity.this);
        myCursor=db.select();
        SimpleCursorAdapter adpater=new SimpleCursorAdapter(this
        		, R.layout.test, myCursor,
        		new String[]{dbHelper.FIELD_TITLE},
        		new int[]{R.id.topTextView});
        myListView.setAdapter(adpater);
        
        myListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				myCursor.moveToPosition(arg2);
				_id=myCursor.getInt(0);
				myEditText.setText(myCursor.getString(1));
			}
		});
        
        
        myListView.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				SQLiteCursor sc=(SQLiteCursor)arg0.getSelectedItem();
				_id=sc.getInt(0);
				myEditText.setText(sc.getString(1));
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
    }
    private void operation(String cmd)
    {
    	if(myEditText.getText().toString().equals(""))
    	return;
    	if(cmd=="add")
    		db.insert( myEditText.getText().toString());
    	if(cmd=="edit")
    		db.update(_id,  myEditText.getText().toString());
    	if(cmd=="delete")
    		db.delete(_id);
    	myCursor.requery();
    	myListView.invalidateViews();
    	myEditText.setText("");
    	_id=0;
    	
    }
    
   
    
    
    
    
    
    
    
}

 
数据存储之SQLite

 

你可能感兴趣的:(sql,android,sqlite,OS)