我正在尝试将数据插入sqlite Database
。我正在按照Youtube
教程执行此任务。
我编写了以下代码并成功创建了Sqlite Database file
,但是当我尝试插入数据时,它会给出错误消息。
我写了以下代码。请指导我在这里做错了什么。
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="ep";
public static final String TABLE_NAME= "transactionsHistory";
public static final String ID= "ID";
public static final String MESSAGE= "MESSAGE";
public static final String CREATE_TABLE= "create table "+ TABLE_NAME + " ( "+ID+" INTEGER PRIMARY KEY AUTO INCREMENT, "+MESSAGE+" TEXT)";
public static final String DROP_TABLE= "DROP TABLE IF EXISTS"+ TABLE_NAME;
private Context context;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null , 1);
SQLiteDatabase db= this.getWritableDatabase();
this.context= context;
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void insertData(DatabaseHelper dbHelper , String Message){
SQLiteDatabase db= dbHelper.getWritableDatabase();
ContentValues contentValues= new ContentValues();
contentValues.put(MESSAGE, Message);
db.insert(TABLE_NAME, null, contentValues);
Log.d("Insert Successfull ", "Value : "+Message + " :Data Inserted");
}
在活动中调用数据库类
public class SuccessActivity extends Activity {
TextView successMessage;
String failureMessage;
DatabaseHelper myDb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_success);
myDb= new DatabaseHelper(this);
myDb.insertData(myDb, "This is a Random Message ");
错误
08-11 13:16:46.883: I/SqliteDatabaseCpp(22338): sqlite returned: error code = 1, msg = no such table: transactionsHistory, db=/data/data/com.example.ep/databases/ep
08-11 13:16:46.903: E/SQLiteDatabase(22338): Error inserting MESSAGE=This is a Random Message
08-11 13:16:46.903: E/SQLiteDatabase(22338): android.database.sqlite.SQLiteException: no such table: transactionsHistory: , while compiling: INSERT INTO transactionsHistory(MESSAGE) VALUES (?)
08-11 13:16:46.903: E/SQLiteDatabase(22338): at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
08-11 13:16:46.903: E/SQLiteDatabase(22338): at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
答案 0 :(得分:6)
由于您的create table
声明中有错误,因此未创建您的表格。 AUTO
和INCREMENT
之间不应有空格 - 即它应该是:
public static final String CREATE_TABLE= "create table "+ TABLE_NAME + " ( "+ID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+MESSAGE+" TEXT)";