0

我有一个包含 100 多个表的预填充数据库文件。我通常使用 SQLiteDatabase 从 db 文件中读取和写入,但目前,我正在检查如何使用 SQLite 包括使用响应式查询等...

问题是关于该主题的所有教程都包含一个用代码创建的数据库,我找不到满足我需要的简单教程

是否有一个简单tutorial/library/guide的方法来使用诸如 SQLite 之类的库和 room 从预填充的数据库中读取/写入,而不必在我的代码中创建数据库表作为类?

也正如标题所说,有没有办法在 SQLite 中使用SQLiteDatabaseSupportSQLiteOpenHelper

4

1 回答 1

0

我有一个类名是 Databaseasset 你可以把你的数据库放在资产文件夹中,然后使用这个类和模型来插入更新或......表在这里我的数据库资产

package appdesin.myapp.database;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseAssets extends SQLiteOpenHelper {
String DB_PATH = null;
//here name of your database
private static String DB_NAME = "appdb";
// and here define your tables
public static final String TABLE_USERS = "users_tbl";
public static final String TABLE_PRODUCT = "product_tbl";

// TABLE_CONTENT

private SQLiteDatabase myDataBase;
private final Context myContext;

/**
 * Constructor Takes and keeps a reference of the passed context in order to
 * access to the application assets and resources.
 * 
 * @param context
 */
@SuppressLint("SdCardPath")
public DatabaseAssets(Context context) {

    super(context, DB_NAME, null, 1);//1 is database  version
    this.myContext = context;
    // DB_PATH = "/data/data/" + context.getPackageName() + "/" +
    // "databases/";
    DB_PATH = "/data/data/" + myContext.getPackageName() + "/" + "databases/";
}

/**
 * Creates a empty database on the system and rewrites it with your own
 * database.
 * */
public void createDataBase() throws IOException {

    boolean dbExist = checkDataBase();

    if (dbExist) {
        // do nothing - database already exist
    } else {

        // By calling this method and empty database will be created into
        // the default system path
        // of your application so we are gonna be able to overwrite that
        // database with our database.
        this.getReadableDatabase();

        try {

            copyDataBase();

        } catch (IOException e) {

            throw new Error("Error copying database");

        }
    }

}

private boolean checkDataBase() {

    SQLiteDatabase checkDB = null;

    try {
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READONLY
                        | SQLiteDatabase.NO_LOCALIZED_COLLATORS
                        | SQLiteDatabase.CREATE_IF_NECESSARY);

    } catch (SQLiteException e) {

        // database does't exist yet.

    }

    if (checkDB != null) {

        checkDB.close();

    }

    return checkDB != null ? true : false;
}

/**
 * Copies your database from your local assets-folder to the just created
 * empty database in the system folder, from where it can be accessed and
 * handled. This is done by transfering bytestream.
 * */
public void copyDataBase() throws IOException {

    // Open your local db as the input stream
    InputStream myInput = myContext.getAssets().open(DB_NAME);

    // Path to the just created empty db
    String outFileName = DB_PATH + DB_NAME;

    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();

}

public void openDataBase() throws SQLException {

    // Open the database
    String myPath = DB_PATH + DB_NAME;
    // SQLiteDatabase.NO_LOCALIZED_COLLATORS
    myDataBase = SQLiteDatabase.openDatabase(myPath, null,
            SQLiteDatabase.OPEN_READONLY
                    | SQLiteDatabase.NO_LOCALIZED_COLLATORS
                    | SQLiteDatabase.CREATE_IF_NECESSARY);

}

@Override
public synchronized void close() {

    if (myDataBase != null)
        myDataBase.close();

    super.close();

}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

创建模型和动作类

这是我的动作课

package appdesin.myapp.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;

import appdesin.myapp.models.Products;

/**
 * Created by hp on 7/4/2018.
 */

public class ProductActions extends DatabaseAssets {
/**
 * Constructor Takes and keeps a reference of the passed context in order to
 * access to the application assets and resources.
 *
 * @param context
 */

public  static String KEY_ID="id";
public  static String KEY_TITLE="title";
public  static String KEY_DES="des";
public  static String KEY_RATE="rate";
public  static String KEY_IMAGE_PATH="image_path";
public  static String KEY_ICON="image_icons";
public  static String KEY_PRICE="price";
public  static String KEY_PRODCUTDATE="product_date";

public ProductActions(Context context) {
    super(context);
}


public long InsertProduct(Products products)
{
    SQLiteDatabase db=getWritableDatabase();
    ContentValues values=new ContentValues();
    values.put(KEY_TITLE,products.getTitle());
    values.put(KEY_DES,products.getDes());
    values.put(KEY_RATE,products.getRate());
    values.put(KEY_ICON,products.getImage());
    return db.insert(TABLE_PRODUCT,null,values);

}

public long updateProduct(Products products)
{
    SQLiteDatabase db=getWritableDatabase();
    ContentValues values=new ContentValues();
    values.put(KEY_ID,products.getId());
    values.put(KEY_TITLE,products.getTitle());
    values.put(KEY_DES,products.getDes());
    values.put(KEY_RATE,products.getRate());
    values.put(KEY_ICON,products.getImage());
    return db.update(TABLE_PRODUCT,values,""+KEY_ID+"="+products.getId()+"" ,mull);

}

public int deleteId(int id)
{
    SQLiteDatabase db=getWritableDatabase();
    return db.delete(TABLE_PRODUCT,""+KEY_ID+"="+id+"",null);



}

public ArrayList<Products> getAllProducts()
{
    SQLiteDatabase db=getReadableDatabase();
    String  query="select * from " + TABLE_PRODUCT;
     Cursor cursor= db.rawQuery(query,null);

    ArrayList<Products> productsArrayList=new ArrayList<>();

    while(cursor.moveToNext())
    {
        Products products=new Products();
        int id=cursor.getInt(cursor.getColumnIndex(KEY_ID));
        String title=cursor.getString(cursor.getColumnIndex(KEY_TITLE));
        String des=cursor.getString(cursor.getColumnIndex(KEY_DES));
        String rate=cursor.getString(cursor.getColumnIndex(KEY_RATE));
        byte[] image_icon=cursor.getBlob(cursor.getColumnIndex(KEY_ICON));

        products.setId(id);
        products.setTitle(title);
        products.setDes(des);
        products.setRate(rate);
        products.setImage(image_icon);
        productsArrayList.add(products);

    }
    return  productsArrayList;
}

public  Products  getProductId(int id)
{
    SQLiteDatabase db=getReadableDatabase();
    Cursor cursor=db.rawQuery("select * from "+TABLE_PRODUCT+" where "+KEY_ID+"="+id+" ",null);
    Products product=new Products();


    if(cursor.moveToNext()) {
        int myid = cursor.getInt( cursor.getColumnIndex(KEY_ID));

        String title = cursor.getString(cursor.getColumnIndex(KEY_TITLE));
        String des = cursor.getString(cursor.getColumnIndex(KEY_DES));
        String rate = cursor.getString(cursor.getColumnIndex(KEY_RATE));
        byte[] img_icon = cursor.getBlob(cursor.getColumnIndex(KEY_ICON));
        product.setId(myid);
        product.setTitle(title);
        product.setDes(des);
        product.setRate(rate);
        product.setImage(img_icon);
    }

    return  product;
}


}

您可以使用此行将数据库复制到设备的数据文件夹中

 DatabaseAssets databaseAssets = new DatabaseAssets(MainActivity.this);
    try {
        databaseAssets.createDataBase();
    } catch (IOException e) {
        e.printStackTrace();
    }

希望这对您或某人有所帮助

于 2018-11-06T11:16:24.567 回答