我想将数据插入到我的SQLite数据库中。 它由3列命名,id,Questions和Answer。
这是我的addQuestion方法
long addQuestion(addtodb question) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, KEY_NAME); // question Name
values.put(KEY_ANSWER, KEY_ANSWER); // answer
// Inserting Row
return db.insert(TABLE_QUESTIONS, null, values);
//db.close(); // Closing database connection
}
addtodb getQuestion(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_QUESTIONS, new String[] { KEY_ID,
KEY_NAME, KEY_ANSWER }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
addtodb question = new addtodb(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
return question;
}
我用这种方式调用这个方法,
DatabaseHandler db = new DatabaseHandler(this);
long id = db.addQuestion(new addtodb(0, "Question1", "answer1"));
id = db.addQuestion(new addtodb(0, "Question2", "answer2"));
db.close();
我希望记录同样为1, Question1, Answer1
。
但我得到1, Question, Answer
。
我无法弄清楚出了什么问题。
答案 0 :(得分:1)
这是你犯错误的地方,Question1
的问题没有发送,
这是发送Question
values.put(KEY_NAME, KEY_NAME); // question Name
values.put(KEY_ANSWER, KEY_ANSWER); // answer
将此更改为
long addQuestion(String Question, String Answer) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, Question); // question Name
values.put(KEY_ANSWER, Answer); // answer
// Inserting Row
return db.insert(TABLE_QUESTIONS, null, values);
//db.close(); // Closing database connection
}
您的调用方法也可以更改,因为您已经在addQuestion
方法
long id = addQuestion("Question1", "answer1");
id = db.addQuestion("Question2", "answer2");
这将有效
答案 1 :(得分:1)
我认为问题出在以下几行:
values.put(KEY_NAME, KEY_NAME); // question Name
values.put(KEY_ANSWER, KEY_ANSWER); // answer
您没有传递要写入数据库的实际值。 put方法的第二个参数应该是实际值。
values.put(KEY_NAME, "some question value"); // question Name
values.put(KEY_ANSWER, "some answer value"); // answer
答案 2 :(得分:0)
我是分享,您的 Addtodb 类看起来像这样:
public class Addtodb{
int id;
String question;
String answer;
public Addtodb(int id, String question, String answer){
this.id = id;
this.question = question;
this.answer = answer;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
更正将在此处:
long addQuestion(Addtodb question) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, question.getQuestion()); // question Name
values.put(KEY_ANSWER, question.getAnswer()); // answer
// Inserting Row
return db.insert(TABLE_QUESTIONS, null, values);
//db.close(); // Closing database connection
}