Android:将数据保存到SQLite数据库中

时间:2013-07-26 21:13:48

标签: android android-sqlite

我正在尝试将一些数据从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);
    }

}

然后我想用这段代码保存我的Activity中的一些数据:

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变量中创建此列,我不会在我的数据库中创建一个列,但是如何创建它?

2 个答案:

答案 0 :(得分:0)

我只是在这里猜测,但可能是你之前使用不同的表结构运行应用程序?由于您的数据库版本仍为1,因此永远不会调用onUpgrade()onCreate()也没有,因为数据库已经存在。要么增加db版本,要么卸载并重新安装应用程序以确保新创建db。

答案 1 :(得分:0)

public class Sqlitedatabase extends SQLiteOpenHelper {

  public Sqlitedatabase(Context context) {
      super(context, "DoctorDatabase.db", null, 1);
  }

  @Override
  public void onCreate(SQLiteDatabase db) {
      String tableEmp = "create table Doctor(Name text,Number text)";
      db.execSQL(tableEmp);
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  }

  public void insertData(DocotorInformation doctor) {
      SQLiteDatabase db = this.getWritableDatabase();

      ContentValues values = new ContentValues();
      values.put("Name", doctor.getName()); // Contact Name
      values.put("Number", doctor.getNumber()); // Contact Phone Number

      // Inserting Row
      db.insert("Doctor", null, values);
      db.close(); // Closing database connection
  }


  public ArrayList<DocotorInformation> getAllContacts() {
      ArrayList<DocotorInformation> contactList = new ArrayList<DocotorInformation>();
      // Select All Query
      String selectQuery = "SELECT  * FROM Doctor";

      SQLiteDatabase db = this.getWritableDatabase();
      Cursor cursor = db.rawQuery(selectQuery, null);

      // looping through all rows and adding to list
      if (cursor.moveToFirst()) {
          do {
            DocotorInformation contact = new DocotorInformation();
            contact.setName(cursor.getString(0));
            contact.setNumber(cursor.getString(1));

            // Adding contact to list
            contactList.add(contact);
        } while (cursor.moveToNext());
    }

    // return contact list
    return contactList;
    }
}