朋友们! 我试图从xml文件填充一个简单的数据库,但是在标题中收到一个错误,并且在日志中写入,列中的值放错了。
我不明白,问题出在哪里,所以我请求你的帮助。代码如下。 非常感谢。
XML文件:
<?xml version="1.0" encoding="utf-8"?>
<cards>
<record path="R.mipmap.ot1" woman = "wfew" man = "qwe"/>
<record path="R.mipmap.ot2" woman = "rewr" man = "dwd"/>
</cards>
DBhelper类:
class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, "myDB", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(LOG_TAG, "--- onCreate database ---");
db.execSQL("create table mytable ("
+ "id integer primary key autoincrement,"
+ "path text,"
+ "woman text," + "man text" + ");");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
将数据添加到数据库:
Resources res = this.getResources();
ContentValues values = new ContentValues();
XmlResourceParser _xml = res.getXml(R.xml.cardslist);
try {
int eventType = _xml.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if ((eventType == XmlPullParser.START_TAG)
&& (_xml.getName().equals("record"))) {
String path = _xml.getAttributeValue(0);
String woman = _xml.getAttributeValue(1);
String man = _xml.getAttributeValue(2);
values.put("path", path);
values.put("woman", woman);
values.put("man", man);
db.insert("mytable", null, values);
Log.d(LOG_TAG, "success");
}
eventType = _xml.next();
}
}
// Catch errors
catch (XmlPullParserException e) {
Log.e("Test", e.getMessage(), e);
} catch (IOException e) {
Log.e("Test", e.getMessage(), e);
} finally {
// Close the xml file
_xml.close();
}
dbHelper.close();
}
日志错误:
E/SQLiteLog: (1) table mytable has no column named man
E/SQLiteDatabase: Error inserting path=dwd woman=R.mipmap.ot2 man=rewr
android.database.sqlite.SQLiteException: table mytable has no column named man (code 1): , while compiling: INSERT INTO mytable(path,woman,man) VALUES (?,?,?)
答案 0 :(得分:0)
CREATE TABLE IF NOT EXISTS
;
尝试这种方式,只需纠正你的execSQL
陈述。
String sqlStatement = "CREATE TABLE IF NOT EXISTS mytable( id INTEGER PRIMARY KEY AUTOINCREMENT, path TEXT, woman TEXT, man TEXT)";
db.execSQL(sqlStatement);
注意强>
如果出现同样的问题,则需要修改
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// ALTER TABLE LOGIC
}
答案 1 :(得分:0)
您必须卸载您的应用,然后重新安装,因为probabelly您更改了数据库架构,并且在onUpgrade
中您没有增加版本号,请查看this link以了解相关内容在更改架构时要执行的操作