如何在Android中创建数据库?

30

我需要一个逐步操作的过程,用于在Android中创建数据库。


更多信息,我建议您阅读Android文档,网址为http://developer.android.com/training/basics/data-storage/databases.html。它会逐步教您所有内容。祝一切顺利。 - dev4life
2个回答

50

编程中数据库是很重要的一部分,我们的许多代码都需要使用数据进行处理和保存。就像其他编程环境一样,安卓也支持数据库编程。你可以使用安卓支持的默认数据库SQLiteDatabase

SQLiteDatabase中的数据库可以包含多个表。假设我们有一个名为PERSONALDB的数据库和一个名为BIODATA的表。它的结构如下:

_id integer
code string
name string
gender string

_id is for key increment,

codenamegender用于描述person

当程序第一次被调用时,我们必须确保数据库和表已经打开(如果存在)。如果不存在,则必须创建一个数据库和一个表。这里有一个来自Android记事本示例的示例类PersonDbHelper,用于操作表Biodata

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class PersonDbHelper {
    class Row extends Object {
        public long _Id;
        public String code;
        public String name;
        public String gender;
    }

    private static final String DATABASE_CREATE =
        "create table BIODATA(_id integer primary key autoincrement, "
            + "code text not null,"
            + "name text not null"
            +");";

    private static final String DATABASE_NAME = "PERSONALDB";

    private static final String DATABASE_TABLE = "BIODATA";

    private static final int DATABASE_VERSION = 1;

    private SQLiteDatabase db;

    public PersonDbHelper(Context ctx) {
        try {
            db = ctx.openDatabase(DATABASE_NAME, null);
        } catch (FileNotFoundException e) {
            try {
                db =
                    ctx.createDatabase(DATABASE_NAME, DATABASE_VERSION, 0,
                        null);
                db.execSQL(DATABASE_CREATE);
            } catch (FileNotFoundException e1) {
                db = null;
            }
        }
    }

    public void close() {
        db.close();
    }

    public void createRow(String code, String name) {
        ContentValues initialValues = new ContentValues();
        initialValues.put("code", code);
        initialValues.put("name", name);
        db.insert(DATABASE_TABLE, null, initialValues);
    }

    public void deleteRow(long rowId) {
        db.delete(DATABASE_TABLE, "_id=" + rowId, null);
    }

    public List<Row> fetchAllRows() {
        ArrayList<Row> ret = new ArrayList<Row>();
        try {
            Cursor c =
                db.query(DATABASE_TABLE, new String[] {
                    "_id", "code", "name"}, null, null, null, null, null);
            int numRows = c.count();
            c.first();
            for (int i = 0; i < numRows; ++i) {
                Row row = new Row();
                row._Id = c.getLong(0);
                row.code = c.getString(1);
                row.name = c.getString(2);
                ret.add(row);
                c.next();
            }
        } catch (SQLException e) {
            Log.e("Exception on query", e.toString());
        }
        return ret;
    }

    public Row fetchRow(long rowId) {
        Row row = new Row();
        Cursor c =
            db.query(true, DATABASE_TABLE, new String[] {
                "_id", "code", "name"}, "_id=" + rowId, null, null,
                null, null);
        if (c.count() > 0) {
            c.first();
            row._Id = c.getLong(0);
            row.code = c.getString(1);
            row.name = c.getString(2);
            return row;
        } else {
            row.rowId = -1;
            row.code = row.name= null;
        }
        return row;
    }

    public void updateRow(long rowId, String code, String name) {
        ContentValues args = new ContentValues();
        args.put("code", code);
        args.put("name", name);
        db.update(DATABASE_TABLE, args, "_id=" + rowId, null);
    }
    public Cursor GetAllRows() {
        try {
            return db.query(DATABASE_TABLE, new String[] {
                    "_id", "code", "name"}, null, null, null, null, null);
        } catch (SQLException e) {
            Log.e("Exception on query", e.toString());
            return null;
        }
    }
}
onCreate方法中,您只需要放置下面给出的单个命令来初始化数据库: ...
Db = new PersonDbHelper(this);

它将首先尝试打开'PersonalDB'数据库。如果不存在,则会创建一个数据库。在这个'PersonDbHelper'类中,您有插入、删除、更新和查询表的方法。

这是以上教程的参考:

创建我的第一个Android数据库

您也可以查看以下内容:

http://www.devx.com/wireless/Article/40842

http://www.vogella.de/articles/AndroidSQLite/article.html

希望这可以帮到您。


请您能否简单解释一下这个 SQL 语句的含义?"create table BIODATA(_id integer primary key autoincrement, " + "code text not null," + "name text not null" +");"; 为什么每个列之间需要用 "+" 连接起来? - Time
@时间 你不需要使用 +。它只是用作连接运算符。你可以这样写:"create table BIODATA(_id integer primary key autoincrement, code text not null, name text not null);" - talha2k

7

创建数据库:

db= this.openOrCreateDatabase("db_hw3", MODE_PRIVATE, null); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接