Android中sqlite数据库应用

来源:互联网 发布:linux中文目录改成英文 编辑:程序博客网 时间:2024/06/06 01:42

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);}@Overridepublic void onCreate(SQLiteDatabase db) { //数据第一次 被创建时调用的//生成数据库表//SQLiteDatabase 封装了对数据的所有操作db.execSQL("CREATE TABLE person(personid integer primary key autoincrement, name varchar(20))");}@Overridepublic 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是自动创建的表,记录语言信息。




原创粉丝点击