数据库操作简单示例

 
package mutou.test;

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

public class MySQLiteHelper extends SQLiteOpenHelper {
	public MySQLiteHelper(Context context, String name, CursorFactory factory, int version)
	{
		super(context, name, factory, version);
	}
	
	@Override
	public void onCreate(SQLiteDatabase db)
	{
		db.execSQL("create table if not exists hero_info("
				 + "id integer primary key,"
				 + "name varchar,"
				 + "level integer)");
	}

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


 

 

 

package mutou.test;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;

public class Sample43Activity extends Activity {
    MySQLiteHelper myHelper;
    TextView tv;
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        tv = (TextView)this.findViewById(R.id.tv);
        myHelper = new MySQLiteHelper(this, "my.db", null, 1);
        insertAndUpdateData(myHelper);
        String result = queryData(myHelper);
        tv.setText("名字\t登记\n" + result);
    }
    
    public void insertAndUpdateData(MySQLiteHelper myHelper)
    {
    	SQLiteDatabase db = myHelper.getWritableDatabase();
    	db.execSQL("insert into hero_info(name, level) values('mutou', 1)");
    	
    	ContentValues values = new ContentValues();
    	values.put("name", "music");
    	values.put("level", 2);
    	db.insert("hero_info", "id", values);
    	
    	values.clear();
    	values.put("name", "musicvs");
    	values.put("level", 3);
    	db.update("hero_info", values, "level = 2", null);
    }
    
    public String queryData(MySQLiteHelper myHelper)
    {
    	String result = "";
    	SQLiteDatabase db = myHelper.getReadableDatabase();
    	
    	Cursor cursor = db.query("hero_info", null, null, null, null, null, "id asc");
    	int nameIndex = cursor.getColumnIndex("name");
    	int levelIndex = cursor.getColumnIndex("level");
    	
    	for(cursor.moveToFirst(); cursor.isAfterLast() != true; cursor.moveToNext())
    	{
    		result += cursor.getString(nameIndex) + "	";
    		result += cursor.getString(levelIndex) + "	\n";
    	}
    	
    	cursor.close();
    	db.close();
    	
    	return result;
    }

	@Override
	protected void onDestroy() {
		SQLiteDatabase db = myHelper.getWritableDatabase();	/* 获取数据库对象 */
		//db.delete("hero_info", "1", null);
		super.onDestroy();
	}
    
    
}


 

你可能感兴趣的:(数据库操作简单示例)