我正在尝试将editText中的一些数据保存到基于我的Android设备的SQLite数据库(它应该只基于设备)......所以我创建了DatabaseHelper
类并在那里创建了数据库,这里是这个文件的代码:
package ru.vladimir.droid_spy;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper
{
public static final String TABLE_NAME = "phones";
public static final String COLUMN_PHONES ="phone_number";
private static final String DATABASE_NAME = "trusted_phone.db";
private static final int DATABASE_VERSION = 1;
//create database
private static final String DATABASE_CREATE = "create table " + TABLE_NAME + " ( " + BaseColumns._ID + " integer primary key autoincrement, " + COLUMN_PHONES + " text not null);";
public DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
Log.w(DatabaseHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
然后我想用这段代码从我的活动中保存一些数据:
try
{
DatabaseHelper DBhelper = new DatabaseHelper(getBaseContext());
//put DB in write mode
SQLiteDatabase db = DBhelper.getWritableDatabase();
//put variables
ContentValues values = new ContentValues();
//values.put(DatabaseHelper.COLUMN_ID, 1);
values.put(DatabaseHelper.COLUMN_PHONES, txt_phone.getText().toString());
//insert variables into DB
long query = db.insert(DatabaseHelper.TABLE_NAME, null, values);
//close DB
db.close();
}
catch(Exception e)
{
System.out.println("Error: "+e.getLocalizedMessage());
}
但是当我看到 LogCat 日志时,出现了一条错误消息:
07-27 00:04:50.463: E/SQLiteDatabase(15075): Error inserting phone_number=WEB
07-27 00:04:50.463: E/SQLiteDatabase(15075): android.database.sqlite.SQLiteException: table phones has no column named phone_number: , while compiling: INSERT INTO phones(phone_number) VALUES (?)
我认为这个错误说明我没有在我的数据库中创建一个列,但是如果我在CREATE_DATABASE
变量中创建这个列,我怎么不能创建它?