android sqlite数据库

阅读更多
DBHelper.java
package com.sqlite_02;

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

public class DBHelper extends SQLiteOpenHelper{

	public DBHelper(Context context) {
		super(context, "my_db", null, 1);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL("create table user(_id integer,name text)");
	}

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

}




MainActivity.java
package com.sqlite_02;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        DBHelper helper=new DBHelper(this);
        SQLiteDatabase db=helper.getReadableDatabase();
        
        db.beginTransaction();
        db.execSQL("insert into user values(?,?)", new Object[]{1,"aaaa"});
        db.execSQL("insert into user values(?,?)", new Object[]{2,"cccc"});
        db.setTransactionSuccessful();
        db.endTransaction();
        
        Cursor cursor=db.rawQuery("select * from user",null);
        while(cursor.moveToNext()){
        	String name=cursor.getString(cursor.getColumnIndex("name"));
        	Toast.makeText(this,name,Toast.LENGTH_LONG).show();
        }
        
        db.close();
        
        
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
}

  • com.sqlite_02.rar (684 KB)
  • 下载次数: 4

你可能感兴趣的:(sqlite,android数据库,sqlite数据库)