如果要维护表数据,可以将其转储到 CSV 文件中,然后在创建表后将其插入回来。(无需将数据转储到服务器)这里是转储数据的示例代码。您可以将文件名设置为表名。游标是从 getAll 语句创建的
public boolean createCsvSaveToFile(Cursor cursor, String fileName) throws IOException {
String csv = "";
int colunmCount = cursor.getColumnCount();
/* check if extarnal drive is readerble */
if (!isExternalStorageWritable()) {
fileError = "can not save to external storage";
fileinfo = "Please mount your SD card";
return false;
} else {
/* create the CSV */
for (int i = 0; i < colunmCount; i++) {
csv += QUOTES + cursor.getColumnName(i).toString() + QUOTES + INNER_DELIMITER;
}
csv = csv.replaceAll(",$", "");
csv += LINE_END;
if (cursor.moveToFirst()) {
do {
for (int i = 0; i < colunmCount; i++) {//GET COLUNM values
csv += QUOTES + cursor.getString(i) + QUOTES + INNER_DELIMITER;
}
csv = csv.replaceAll(",$", "");
csv += LINE_END;
} while (cursor.moveToNext());
}
/* save file */
File file = getDataDir(fileName);
FileOutputStream out = new FileOutputStream(file);
out.write(csv.getBytes());
out.flush();
out.close();
return true;
}
}
这是插入数据的示例代码。假设 CSV 文件名与表名相同
private void readFromFile(SQLiteDatabase database, File file) {
boolean hasColunms = false;
String tableName = file.getName().replaceAll(".csv$", "");
String sql;
String colunmNames = "";
String colunmValues;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
if (!hasColunms ) {
/* get column names */
line = line.replaceAll("\"", "");
colunmNames = line;
hasColunms = true;
} else {
line = line.replaceAll("\"", "'");
colunmValues = line;
sql = "INSERT INTO " + tableName + " (" + colunmNames + ") VALUES (" + colunmValues + ")";
database.execSQL(sql);
}
}
br.close();
} catch (IOException e) {
database.close();
/* You may need to add proper error handling here
}
要遍历许多 csv 文件,可以使用以下代码
public boolean csvTodatabase(SQLiteDatabase database) {
FileStuff f = new FileStuff();
File time;
/* check if extarnal drive is readerble */
if (!f.isExternalStorageReadable()) {
f.fileError = "can not read external storage";
f.fileinfo = "Please remount your SD card";
return false;
} else {
/* get all files from extarnal drive data */
ArrayList<File> files = new ArrayList<File>();
File directory = new File(FileStuff.DATA_DIRECTORY);
if (!directory.exists()) {
return false;
}
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
files.add(file);
}
}
for (File csvfile : files) {
readFromFile(database, csvfile);
}
return true;
}
}
注意: readFromFile(database, csvfile); 是前一个函数