首页 > 代码库 > Android-Sqlite数据库_创建数据库操作Demo

Android-Sqlite数据库_创建数据库操作Demo

技术分享

代码

Activity01

package com.lxt008;import android.app.Activity;import android.database.Cursor;import android.graphics.Color;import android.os.Bundle;import android.view.KeyEvent;import android.widget.LinearLayout;import android.widget.ListAdapter;import android.widget.ListView;import android.widget.SimpleCursorAdapter;public class Activity01 extends Activity{    private static int            miCount            = 0;        /* 线性布局 */    LinearLayout                m_LinearLayout    = null;    /* 列表视图-显示数据库中的数据 */    ListView                    m_ListView        = null;        MyDataBaseAdapter m_MyDataBaseAdapter;    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState)    {        super.onCreate(savedInstanceState);        /* 创建LinearLayout布局对象 */        m_LinearLayout = new LinearLayout(this);        /* 设置布局LinearLayout的属性 */        m_LinearLayout.setOrientation(LinearLayout.VERTICAL);        m_LinearLayout.setBackgroundColor(android.graphics.Color.BLACK);        /* 创建ListView对象 */        m_ListView = new ListView(this);        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);        m_ListView.setBackgroundColor(Color.BLACK);        /* 添加m_ListView到m_LinearLayout布局 */        m_LinearLayout.addView(m_ListView, param);        /* 设置显示m_LinearLayout布局 */        setContentView(m_LinearLayout);                /* 构造MyDataBaseAdapter对象 */        m_MyDataBaseAdapter = new MyDataBaseAdapter(this);                /* 取得数据库对象 */        m_MyDataBaseAdapter.open();                UpdataAdapter();    }        public boolean onKeyUp(int keyCode, KeyEvent event)    {        switch (keyCode)        {            case KeyEvent.KEYCODE_DPAD_LEFT:                AddData();                break;            case KeyEvent.KEYCODE_DPAD_RIGHT:                DeleteData();                break;            case KeyEvent.KEYCODE_1:                UpData();                break;        }        return true;    }        /* 更新一条数据 */    public void UpData()    {            m_MyDataBaseAdapter.updateData(miCount - 1, miCount, "修改后的数据" + miCount);        UpdataAdapter();    }    /* 向表中添加一条数据 */    public void AddData()    {        m_MyDataBaseAdapter.insertData(miCount, "测试数据库数据" + miCount);        miCount++;        UpdataAdapter();    }    /* 从表中删除指定的一条数据 */    public void DeleteData()    {        /* 删除数据 */        m_MyDataBaseAdapter.deleteData(miCount);        miCount--;        if (miCount < 0)        {            miCount = 0;        }        UpdataAdapter();    }        /* 按键事件处理 */    public boolean onKeyDown(int keyCode, KeyEvent event)    {        if (keyCode == KeyEvent.KEYCODE_BACK)        {            /* 退出时,不要忘记关闭 */            m_MyDataBaseAdapter.close();            this.finish();            return true;        }        return super.onKeyDown(keyCode, event);    }        /* 更行试图显示 */    public void UpdataAdapter()    {        // 获取数据库Phones的Cursor        Cursor cur = m_MyDataBaseAdapter.fetchAllData();        miCount = cur.getCount();        if (cur != null && cur.getCount() >= 0)        {            // ListAdapter是ListView和后台数据的桥梁            ListAdapter adapter = new SimpleCursorAdapter(this,            // 定义List中每一行的显示模板                // 表示每一行包含两个数据项                android.R.layout.simple_list_item_2,                // 数据库的Cursor对象                cur,                // 从数据库的TABLE_NUM和TABLE_DATA两列中取数据                new String[] {MyDataBaseAdapter.KEY_NUM, MyDataBaseAdapter.KEY_DATA },                // 与NAME和NUMBER对应的Views                new int[] { android.R.id.text1, android.R.id.text2 });            /* 将adapter添加到m_ListView中 */            m_ListView.setAdapter(adapter);        }    }}

MyDataBaseAdapter

package com.lxt008;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.SQLException;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class MyDataBaseAdapter{    // 用于打印log    private static final String    TAG                = "MyDataBaseAdapter";    // 表中一条数据的名称    public static final String    KEY_ID        = "_id";                                                    // 表中一条数据的内容    public static final String    KEY_NUM        = "num";                                                    // 表中一条数据的id    public static final String    KEY_DATA        = "http://www.mamicode.com/data";    // 数据库名称为data    private static final String    DB_NAME            = "Examples_06_06.db";        // 数据库表名    private static final String    DB_TABLE        = "table1";        // 数据库版本    private static final int    DB_VERSION        = 1;    // 本地Context对象    private Context                mContext        = null;        //创建一个表    private static final String    DB_CREATE        = "CREATE TABLE " + DB_TABLE + " (" + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NUM + " INTERGER,"+ KEY_DATA + " TEXT)";    // 执行open()打开数据库时,保存返回的数据库对象    private SQLiteDatabase        mSQLiteDatabase    = null;    // 由SQLiteOpenHelper继承过来    private DatabaseHelper        mDatabaseHelper    = null;            private static class DatabaseHelper extends SQLiteOpenHelper    {        /* 构造函数-创建一个数据库 */        DatabaseHelper(Context context)        {            //当调用getWritableDatabase()             //或 getReadableDatabase()方法时            //则创建一个数据库            super(context, DB_NAME, null, DB_VERSION);                                }        /* 创建一个表 */        @Override        public void onCreate(SQLiteDatabase db)        {            // 数据库没有表时创建一个            db.execSQL(DB_CREATE);        }        /* 升级数据库 */        @Override        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)        {            db.execSQL("DROP TABLE IF EXISTS notes");            onCreate(db);        }    }        /* 构造函数-取得Context */    public MyDataBaseAdapter(Context context)    {        mContext = context;    }    // 打开数据库,返回数据库对象    public void open() throws SQLException    {        mDatabaseHelper = new DatabaseHelper(mContext);        mSQLiteDatabase = mDatabaseHelper.getWritableDatabase();    }    // 关闭数据库    public void close()    {        mDatabaseHelper.close();    }    /* 插入一条数据 */    public long insertData(int num, String data)    {        ContentValues initialValues = new ContentValues();        initialValues.put(KEY_NUM, num);        initialValues.put(KEY_DATA, data);        return mSQLiteDatabase.insert(DB_TABLE, KEY_ID, initialValues);    }    /* 删除一条数据 */    public boolean deleteData(long rowId)    {        return mSQLiteDatabase.delete(DB_TABLE, KEY_ID + "=" + rowId, null) > 0;    }    /* 通过Cursor查询所有数据 */    public Cursor fetchAllData()    {        return mSQLiteDatabase.query(DB_TABLE, new String[] { KEY_ID, KEY_NUM, KEY_DATA }, null, null, null, null, null);    }    /* 查询指定数据 */    public Cursor fetchData(long rowId) throws SQLException    {        Cursor mCursor =        mSQLiteDatabase.query(true, DB_TABLE, new String[] { KEY_ID, KEY_NUM, KEY_DATA }, KEY_ID + "=" + rowId, null, null, null, null, null);        if (mCursor != null)        {            mCursor.moveToFirst();        }        return mCursor;    }    /* 更新一条数据 */    public boolean updateData(long rowId, int num, String data)    {        ContentValues args = new ContentValues();        args.put(KEY_NUM, num);        args.put(KEY_DATA, data);        return mSQLiteDatabase.update(DB_TABLE, args, KEY_ID + "=" + rowId, null) > 0;    }    }

 

布局

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    ><TextView      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:text="@string/hello"    /></LinearLayout>

 

Android-Sqlite数据库_创建数据库操作Demo