gpt4 book ai didi

android - 如何从保存在android中sd卡中的文本文件创建sqlite数据库或表?

转载 作者:搜寻专家 更新时间:2023-11-01 07:37:44 26 4
gpt4 key购买 nike

我在 SD 卡中有文本文件,其中第一行包含表的列名,其余行包含列的值。每行由/n 分隔,每一项由 | 分隔。通过使用它,我必须在我的数据库中创建一个表。

最佳答案

首先,您必须创建数据库和表来存储文本文件中的数据,如下所示,

public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";

/**
* @param context Application Context
*/
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}

/* Called when the database is created for the first time.
* @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
*/
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE DB_TABLE(_id INTEGER PRIMARY KEY AUTOINCREMENT, content TEXT);");
}

/* Called when the database needs to be upgraded.
* @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w("DatabaseHelper", "Upgrading database, which will destroy all old data");
onCreate(db);
}
}

然后你必须从SD卡中读取文本文件并将记录插入到上面创建的表中,

定义两个变量,

   DatabaseHelper databaseHelper;
SQLiteDatabase db;

在onCreate方法中启动它们,

databaseHelper = new DatabaseHelper(context);
db = databaseHelper.getWritableDatabase();

定义将数据保存到数据库的方法

void saveDataToDB()
{
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//Read text from file
StringBuilder text = new StringBuilder();

try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;

while ((line = br.readLine()) != null) {
insertRecordToDB(columnName, columnValue);
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
}

void insertRecordToDB(columnName, columnValue)
{
ContentValues values = new ContentValues();
values.put(columnName, columnaValue);

db.insert(DB_TABLE, null, values);
}

关于android - 如何从保存在android中sd卡中的文本文件创建sqlite数据库或表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8396191/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com