我一直在努力在Android应用程序中创建SQLite数据库。 我看过许多教程,以及关于堆栈溢出和其他站点的许多现有问题。
这是我的DatabaseHelper类
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
public SQLiteDatabase db;
public static final String DATABASE_NAME = "user.db";
//Module table
public static final String MODULE_TABLE = "modules_table";
public static final String MODULE_COL_1 = "ID";
public static final String MODULE_COL_2 = "CODE";
public static final String MODULE_COL_3 = "TITLE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
Log.d("SQL", "SQLite dbhelper");
db = getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
//db.execSQL("create table " + MODULE_TABLE + "(" + MODULE_COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT, " + MODULE_COL_2 + " TEXT, " + MODULE_COL_3 + " TEXT " +")");
db.execSQL("create table modules_table (ID INTEGER PRIMARY KEY
AUTOINCREMENT, CODE TEXT, TITLE TEXT)");
Log.d("SQL", "SQLite onCreate");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + MODULE_TABLE);
onCreate(db);
}
}
我设法使SQLite dbhelper出现在logcat中,但无法使SQLite onCreate出现,并且无法在文件浏览器或设备本身(无论是模拟设备还是真实设备)中的任何位置找到该数据库。
任何帮助将不胜感激,对于代码格式化,我们深表歉意!
答案 0 :(得分:2)
我建议在活动中使用以下(临时):-
DatabaseHelper myDBHelper = new DatabaseHelper(this); //<<<<<<<<< you appear to already have the equivalent of this line (if so use whatever variable name you have given to the DatabaseHelper object)
Cursor csr = myDBHelper.getWritableDatabase().query("sqlite_master",null,null,null,null,null,null);
DatabaseUtils.dumpCursor(csr);
csr.close();
运行,然后检查日志。您应该看到 modules_table 和 sqlite_sequence 的输出(后者是因为您已经编码了自动增量。
sqlite_master 是一个系统表,用于存储系统信息,例如表和索引名(即架构)。
在未植根的设备上,每个应用程序数据(数据/数据)均受到保护,因此您将无法看到数据库文件。
在仿真器上,它取决于仿真器。我相信更高版本的Android Studio现在允许访问,例如:-
请注意,以上是Android 10.1 Pie(API 28),因此数据库具有预写日志记录(WAL),因此-shm和-wal文件也存在。
该软件包是mjt.pvcheck。完整路径是data / data / mjt.pvcheck / databases。
答案 1 :(得分:1)
我不使用类似SQL的查询
db.execSQL("create table modules_table (ID INTEGER PRIMARY KEY
AUTOINCREMENT, CODE TEXT, TITLE TEXT)");
Log.d("SQL", "SQLite onCreate");
相反,我正在使用自己的SQLiteOpenHelper类实现
import android.content.Context;
import android.content.res.AssetManager;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.zip.GZIPOutputStream;
public class DbProvider extends SQLiteOpenHelper {
private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock(true);
private static final int VERSION = 0;
private final String DB_NAME = "mydb";
private final AssetManager assets;
private DbProvider(Context context) {
super(context, DB_NAME, null, VERSION);
assets = context.getAssets();
}
@NonNull
public static DbProvider getInstance() {
return new DbProvider(App.getContext());
}
@NonNull
public static ReentrantReadWriteLock.WriteLock writeLock() {
return LOCK.writeLock();
}
@NonNull
public static ReentrantReadWriteLock.ReadLock readLock() {
return LOCK.readLock();
}
@NonNull
public static ReentrantReadWriteLock getLock() {
return LOCK;
}
public static void close(DbProvider instance) {
try {
instance.close();
} catch (Exception ex) {
}
}
@Override
public void onCreate(SQLiteDatabase db) {
executeQuery(db, "db-scripts/database.sql", false);
Log.w("database", "database create");
executeQuery(db, "db-scripts/database_updates.sql", true);
Log.w("database", "database update");
}
private void executeQuery(SQLiteDatabase db, String sql, boolean shouldHandleExceptions) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader(assets.open(sql)));
String line;
File tempDbScript = new File(Environment.getExternalStorageDirectory(), "iErunt/dbBackup");
tempDbScript.getParentFile().mkdirs();
tempDbScript.createNewFile();
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tempDbScript));
while ((line = bufferedReader.readLine()) != null) {
line = line.replaceAll("\t+", " ").replaceAll("\n+", " ").replaceAll(" +", " ").replaceAll(";", ";\n");
if (line.startsWith("--") || line.isEmpty()) {
continue;
}
bufferedWriter.write(line);
bufferedWriter.flush();
}
bufferedWriter.close();
bufferedReader.close();
bufferedReader = new BufferedReader(new FileReader(tempDbScript));
db.beginTransaction();
while ((line = bufferedReader.readLine()) != null) {
if (!(line = line.trim().replace(";", "")).isEmpty()) {
if (shouldHandleExceptions) {
try {
db.execSQL(line);
} catch (SQLException ex) {
Log.e("database", ex.getMessage(), ex);
}
} else {
db.execSQL(line);
}
}
}
db.setTransactionSuccessful();
db.endTransaction();
tempDbScript.delete();
} catch (IOException ex) {
Log.e("database", ex.getMessage(), ex);
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
}
}
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
executeQuery(db, "db-scripts/database_updates.sql", true);
}
}
并将数据库的初始数据库架构放入assets/db-scripts/database.sql
中
并且只要您进行数据库修改,就将您的alter查询放入assets/db-scripts/database_updates.sql
中。更新数据库时,请确保增加数据库的VERSION
。
此类的作用是读取整个SQL脚本并逐个执行。大大减少了开发时间。
注意:您将需要android.permission.WRITE_EXTERNAL_STORAGE
权限,因为这会创建一个临时文件并在最后将其删除
希望这会有所帮助!