我有一个预填充的数据库文件,其中包含100多个表。我通常使用SQLiteDatabase来读取和写入数据库文件,但目前,我正在检查如何使用SQLite来包括使用反应式查询等
问题是,所有关于这个主题的教程都包括一个用代码创建的数据库,我找不到一个简单的教程来满足我的需求
有没有一个简单的tutorial/library/guide
,说明如何使用像SQLite和room这样的库从预先填充的数据库中读/写,而不必在我的代码中创建数据库表作为类?
正如标题所说,是否有一种方法可以将SQLiteDatabase
转换为SupportSQLiteOpenHelper
以在SQLite中使用。
我有一个类名是Databaseasset,您可以将数据库放在asset文件夹中,然后使用这个类和模型插入更新或。。。表这是我的数据库资产
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();
}
希望这能帮助你或某个