SQLiteDatabase: 轻量级的关系数据库
特点:轻量级、独立性、隔离性、跨平台、多语言接口、安全
利用命令行操作:
ls:可显示下面的全部内容
adb shell
ls
cd data
cd data
cd 包名
cd database
可以看见
database.db
用sqlite3 database.db 进入数据库
sql语句就可以增删改查
一: 直接对现有的数据库
SQLiteDatabase db = openOrCreateDatabase("database.db",MODE_PRIVATE,null);
db.execSQL("create table TABLENAME (COLUMNNAME varchar(20),.....)");
二。继承SQLiteOpenHelper 重写onCreate(初始化执行,只执行一次) 和 onUpgrade(Version 发生改变时执行)方法
使用:
<span style="font-family: Arial, Helvetica, sans-serif;">MyDBHelper helper = </span><span style="font-family: Arial, Helvetica, sans-serif;">MyDBHelper .getInstance(getContext());</span>
<span style="font-family: Arial, Helvetica, sans-serif;">SQLiteDatabase db = helper.getWritableDatabase();//写入方式打开,若磁盘已满会报错</span>=helper.getReadableDatabase(); //先以写入方式得到,若磁盘满,就以只读方式打开
db.execSQL("SQL语句");
安卓的方式对数据库进行增删改查
db.query()/db.insert()/db.update()/db.delete();
Cursor cursor = db.query("tableName",null,null,nul.....);
返回的是游标Cursor
if (<span style="font-size:14px;">cursor </span>!= null && <span style="font-size:14px;">cursor</span>.getCount() > 0) { <span style="white-space:pre"> </span>while (<span style="font-size:14px;">cursor</span>.moveToNext()) { <span style="white-space:pre"> </span>String name = <span style="font-size:14px;">cursor</span>.getString(<span style="font-size:14px;">cursor</span>.getColumnIndex("columnname")); <span style="white-space:pre"> </span>String sex = <span style="font-size:14px;">cursor</span>.getString(<span style="font-size:14px;">cursor</span>.getColumnIndex("columnname")); } }
public class MyDBHelper extends SQLiteOpenHelper{ private static MyDBHelper sHelper; public static final String DB_NAME = "student_database.db"; public static MyDBHelper getInstance(Context context){ if (sHelper ==null) { sHelper = new MyDBHelper(context); } return sHelper; } private MyDBHelper(Context context) { super(context, DB_NAME, null, ColumnData.StudentTable.STUDENT_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table student ("+ColumnData.StudentTable.COLUMN_ID+" int,"+ColumnData.StudentTable.COLUMN_NAME+" varchar(20))"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }