我是数据库的新手。目前我已经创建了一个应用程序,我想将它链接到SQLite数据库。在youtube上关注教程之后,我尝试添加一个简单的行来测试我的数据库。我收到错误E/SQLiteLog: (1) no such table: SCORES
E/SQLiteDatabase: Error inserting DScore=0 LScore=0 Name=Aris
这是我现在的代码:
public class DB_Controller {
private DB_Scores helper;
public DB_Controller(Context context) {
helper = new DB_Scores(context);
}
public long insertRow(String name){
SQLiteDatabase db=helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DB_Scores.NAME, name);
values.put(DB_Scores.DSCORE, 0);
values.put(DB_Scores.LSCORE, 0);
long id = db.insert(DB_Scores.TABLE_NAME,null, values);
return id;
}
static class DB_Scores extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "scores.db";
private static final String TABLE_NAME = "SCORES";
private static final int DATABASE_VERSION = 1;
private static final String UID = "_id";
private static final String NAME = "Name";
private static final String LSCORE = "LScore";
private static final String DSCORE = "DScore";
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+UID+" INTEGER PRIMARY KEY " +
"AUTOINCREMENT, "+NAME+" TEXT UNIQUE, "
+LSCORE+" INTEGER, "+DSCORE+" INTEGER);";
private Context context;//?
public DB_Scores(Context context ) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
Toast.makeText(context, "Constructor was called", Toast.LENGTH_LONG).show();
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
Toast.makeText(context, "onCreate was called", Toast.LENGTH_LONG).show();
} catch (SQLException e) {
Toast.makeText(context, ""+e, Toast.LENGTH_LONG).show();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try{
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
Toast.makeText(context, "onUpgrade called", Toast.LENGTH_LONG).show();
onCreate(db);
}catch(SQLException e){
Toast.makeText(context, ""+e, Toast.LENGTH_LONG).show();
}
}
}
}
我创建DB_Controller对象的活动
public class Scores_Activity extends AppCompatActivity {
private DB_Controller dbController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scores_activity);
dbController = new DB_Controller(this);
addRow();
}
public void addRow() {
long id=dbController.insertRow("Aris");
if (id < 0) {
Toast.makeText(this, "Unsuccessful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
}
}
它标记为错误来源的行是long id=dbController.insertRow("Aris");
,
long id = db.insert(DB_Scores.TABLE_NAME,null, values);
和addRow();
我的猜测是我在创建数据库时出现了逻辑错误。感谢您的时间
答案 0 :(得分:-2)
更改create table命令,如下所示(不需要在查询末尾加分号)
private static final String CREATE_TABLE="CREATE TABLE "+TABLE_NAME+" ("+UID+" INTEGER PRIMARY KEY " +
"AUTOINCREMENT, "+NAME+" TEXT UNIQUE, "
+LSCORE+" INTEGER, "+DSCORE+" INTEGER )";