android下的轻量级Sqlite创建数据库

android的开发创建一个数据库

实现的步骤
1、创建一个类继承抽象类SqliteOpenHelper
实现两个方法onCreate()和onUpgrade()
2、实例化这个类,创建出一个对象。这个对象调用getReadableDatabase()方法,实现数据库的创建并打开
在调用了getReadableDatabase()后会调用对象中的onCreate()和onUpgrade()


package com.alleged.database;


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


public class DataBase extends SQLiteOpenHelper {


public DataBase(Context context) {
//context:上下文   name:数据库名称  factory:用来创建cursor对象,默认为空 null version 数据的版本号,从1开始
super(context, "alleged.db", null, 1);

}


@Override
public void onCreate(SQLiteDatabase db) {
//onCreate方法用来创建表 
//SQLiteDatabase db用来执行相应的sql语句
db.execSQL("create table info (_id integer primary key autoincrement,name varchar(20))");
System.out.println("test info creat is ok");
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//这个方法是用来更改表的结构
System.out.println(oldVersion+"v"+newVersion);
}


}




package com.alleged.database;


import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends ActionBarActivity {


private Context mcontext;
@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mcontext = this;
System.out.println("123455");
DataBase db = new DataBase(mcontext);
SQLiteDatabase db1 = db.getReadableDatabase();
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值