Android Sqlite数据库

public class MainActivity extends AppCompatActivity {

    Mydata shp;
    SQLiteDatabase sdb;
    ListView lv;
    Cursor cursor;
    ListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lv=(ListView) findViewById(R.id.lv);

        shp=new Mydata(this,"students",null,2);
        sdb=shp.getWritableDatabase();

        cursor=sdb.rawQuery("select * from students",null);
        if(cursor!=null)
            adapter=new SimpleCursorAdapter(this,R.layout.mylist,cursor,new String[]{"_id","sname"},new int[]{R.id.tid,R.id.tname});
        lv.setAdapter(adapter);
    }
}

//SQLiteOpenHelper是数据库管理的帮助类
public class Mydata extends SQLiteOpenHelper{

    public static final String CREATE_BOOK = "create table Book("
            +"id integer primart key autoincrement, "
            +"author text,"
            +"price real,"
            +"pages integer,"
            +"name text)";

    public static final String CREATE_CATEGORY="create table Category("
            +"id integer primary key autoincrement,"
            +"category_name text,"
            +"category_code integer)";

    Context mcontext;

    public Mydata(Context context, String name, SQLiteDatabase.CursorFactory factory,int version){
        super(context,name,factory,version);
        mcontext=context;
    }

    //在调getReadableDatabase或getWritableDatabase时,会判断指定的数据库是否存在,
    // 不存在,onCreate()方法在初次生成数据库时才会被调用
    @Override
    public void onCreate(SQLiteDatabase db) {
        //db.execSQL(CREATE_BOOK);
        db.execSQL("create table if not exists students(_id text,sname text)");
       // db.execSQL(CREATE_CATEGORY);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
         switch (oldVersion){
             case 1:
                 //db.execSQL(CREATE_CATEGORY);
                 db.execSQL("insert into students values('2','b')");
             default:
         }
        onCreate(db);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值