残缺极品 发表于 2016-11-30 09:29:09

Android中sqlite数据库应用

  1、特点
  和其他数据相比是无类型的。可以存放任意类型,但是主键除外。如果主键为:INTEGER PRIMARY KEY,则只能存储64位整数。
  1) Create Table可以用下面的语句:
  CREATE TABLE person(personid integer primary key autocrement, name varchar(20))
  

  后面的varchar(20)建议写上。
  

  2) 获取自增长后的ID值:select last_insert_rowid()
  

  案例:
  1、创建数据库
  SQLiteOpenHelper.getReadableDatabase() 或 getWritableDatabase()
  自动创建数据库。
  

  

package com.tong.service;

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

public class DBOpen extends SQLiteOpenHelper {

public DBOpen(Context context) {
//数据库名tong.db 使用系统默认的游标工厂数据库文件的版本号
super(context, "tong.db", null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) { //数据第一次 被创建时调用的
//生成数据库表
//SQLiteDatabase 封装了对数据的所有操作
db.execSQL("CREATE TABLE person(personid integer primary key autoincrement, name varchar(20))");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //版本号发生变化时调用
//执行更新操作
//添加一个字段
db.execSQL("ALTER TABLE person ADD phone VARCHAR(12) NULL");
}

}


  

  

  

  写一个测试类,创建数据库。
  

package com.tong.test;
import com.tong.service.DBOpen;
import android.test.AndroidTestCase;
public class DBOpenTest extends AndroidTestCase {
public void testCreateDB() throws Exception{
DBOpen dbopen = new DBOpen(getContext());
// 自动创建数据库
dbopen.getReadableDatabase();
}
}

  


别忘了配置文件,加入单元测试:  <?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.dbapp"

android:versionCode="1"

android:versionName="1.0" >



<uses-sdk

android:minSdkVersion="8"

android:targetSdkVersion="17" />



<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name="com.tong.dbapp.MainActivity"

android:label="@string/app_name" >

<intent-filter>

<action android:name="android.intent.action.MAIN" />



<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<uses-library android:name="android.test.runner"/>


</application>
<instrumentation android:name="android.test.InstrumentationTestRunner"

android:targetPackage="com.example.dbapp" android:label="Test Tong App">

</instrumentation>

</manifest>


  运行测试用例,数据库已经创建好!
  

  

  

  其中的 android_metadata是自动创建的表,记录语言信息。
  

  

  
页: [1]
查看完整版本: Android中sqlite数据库应用