gpt4 book ai didi

java - 将 SQLite 数据库转换为 csv

转载 作者:行者123 更新时间:2023-12-02 05:20:21 24 4
gpt4 key购买 nike

我一直在尝试将 SQLite 数据库列值导出到 log.csv 文件。到目前为止,我已经达到了导出文件但没有任何类型数据的地步。执行该方法后,我在执行 rawQuery 的行上收到 java.lang.NullPointerException 。有人可以在这件事上帮助我吗?

感谢您提前抽出时间、查看并回答此问题。

数据库代码:

public class happinessDb  extends SQLiteOpenHelper {

public static final String KEY_ROWID = "_id";
public static final String KEY_DATE = "date";
public static final String KEY_TIME = "time";
public static final String KEY_HAPPY = "happy";
public static final String KEY_NORMAL = "normal";
public static final String KEY_SAD = "sad";

public static final String DATABASE_NAME = "happinesMeter";
public static final String DATABASE_TABLE = "practiceReport";
public static final int DATABASE_VERSION = 2;

private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;

private static class DbHelper extends SQLiteOpenHelper{

public DbHelper (Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
KEY_DATE + " TEXT NOT NULL, " +
KEY_TIME + " TEXT NOT NULL, " +
KEY_HAPPY + " TEXT NOT NULL, " +
KEY_NORMAL + " TEXT NOT NULL, " +
KEY_SAD + " TEXT NOT NULL);"
);

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}

public happinessDb(Context c){ //Error
ourContext = c;
}
public happinessDb open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}

转换数据库的方法:

 public boolean convertHappiness() {
String FILENAME = "log.csv";
File directoryDownload = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File logDir = new File(directoryDownload, FILENAME);
try {
logDir.createNewFile();
CSVWriter csvWriter = new CSVWriter(new FileWriter(logDir));
Cursor curCSV = ourDatabase.rawQuery("SELECT * FROM practiceReport", null);
csvWriter.writeNext(curCSV.getColumnNames());
while (curCSV.moveToNext()) {
String arrStr[] = { curCSV.getString(1)+ ",", curCSV.getString(2)+ ",",
curCSV.getString(3)+ ",", curCSV.getString(4)+ ",", curCSV.getString(5)+ ","};
csvWriter.writeNext(arrStr);
}
csvWriter.close();
curCSV.close();
return true;
} catch (Exception e) {
Log.e("MainActivity", e.getMessage(), e);
return false;
}

}

最佳答案

在使用此命令之前,您必须初始化数据库变量:

ourDatabase = this.getWritableDatabase();//you missed this line..
Cursor curCSV = ourDatabase.rawQuery("SELECT * FROM practiceReport", null);

关于java - 将 SQLite 数据库转换为 csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26563008/

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