0

嗨,我在 android 中创建了一个 SQLite 数据库,我最初在其中插入了两条记录,但是在执行数据时没有插入数据数据库显示为空。任何人都可以帮我插入数据

在下面给出我的数据库类

          public class DummyDatabase extends SQLiteOpenHelper{



   public static final int NAME_COLUMN=2;

   static final String DATABASE_NAME = "NestDatabase.db";
  static final int DATABASE_VERSION = 1;
  static final String tableName="Employees";
  static final String DATABASE_CREATE = "create table      "   
           +           "  Employees  "+ " " + "  "
           +       "    (     "    
           +     "   ID   "  
           +     "     integer      primary key autoincrement ,    "   
           +      "             NAME            text     , 
             EMPLOYEE_CODE    text," 
           +      "    MOBILE_NUMBER    integer  ); ";



  public SQLiteDatabase db;
  private final Context context;
  public DataBaseHelper1 dbHelper;

  public DummyDatabase(Context _context) {
        super(_context,DATABASE_NAME, null,DATABASE_VERSION);
        // TODO Auto-generated constructor stub
        context=_context;
        dbHelper=new DataBaseHelper1(_context,DATABASE_NAME, 
          null,DATABASE_VERSION);
    }


  public DummyDatabase open() throws SQLException
    {
        db=dbHelper.getWritableDatabase();
        return this;
    }

    public void close()
    {
        db.close();
    }

    public int deleteEntry(String NAME)
    {

           String where="NAME=?";
           int numberOFEntriesDeleted= db.delete("Employees", where, new String[]
           {NAME}) ;
           Toast.makeText(context, "Number fo Entry Deleted Successfully : 
             "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
        return numberOFEntriesDeleted;

    }
    public String getEntry(String Emp_code)
    {


            Cursor cursor=db.query("Employees", null, " EMPLOYEE_CODE=?", new
             String[]{Emp_code}, null, null, null);
            if(cursor.getCount()<1) // UserName Not Exist
                return "NOT EXIST";
            cursor.moveToFirst();
            String user= cursor.getString(cursor.getColumnIndex("NAME"));
            return user;


    }


      @Override
    public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

    db.execSQL(DATABASE_CREATE);
    db.execSQL("insert into Employees( NAME , EMPLOYEE_CODE , MOBILE_NUMBER)
            "+" values ('Alexander','A111','1234567890');");
    db.execSQL("insert into Employees( NAME , EMPLOYEE_CODE , MOBILE_NUMBER)
             "+" values ('Bernie','B111','1234567890');");
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

        Log.w("TaskDBAdapter","Upgrading from 
       version"+oldVersion+"to"+newVersion+",which will destroy all old data"); 

    db.execSQL("DROP TABLE IF EXISTS"+"TEMPLATE");
    onCreate(db);
   }

        }
4

6 回答 6

2

onCreate您必须在SQLiteOpenHelper的方法中创建数据表。

如果不存在则创建表 DATABASE_CREATE;

将您的插入语句更改

db.execSQL("insert into Employees( NAME , EMPLOYEE_CODE , MOBILE_NUMBER)
             VALUES ('Alexander','A111','1234567890');");
于 2013-09-18T06:27:04.723 回答
1

onCreate仅在第一次创建数据库时调用。所以我的猜测是,数据库存在(来自您的代码的早期运行,此时可能没有插入)并且onCreate根本没有调用。只需添加一个Log.d()onCreate检查。此外,仅定义 acreate table是不够的,您还需要在onCreate():-) 中针对数据库执行它。

更进一步,您应该在代码中更改一些内容。一个或另一个实际上也可以立即解决您的问题。

  • create table表结构(新表、列、视图)的更改应在onCreate和中完成onUpgrade。这是结构更改和初始数据(如插入)的正确位置。
  • 实际上,您onCreate应该只包含该行onUpgrade(db, 0, 1),并且您在onUpgrade.
  • 如果您运行诸如插入、更新、删除(数据操作语言:DML)之类的语句,您应该始终commit在工作。在此之前,数据不会写入磁盘,在下一次运行中您无法再选择它。
  • db.insert在插入行时使用而不是db.execSQL. 它旨在为 Java 程序员提供更简单的界面。
  • 确保您的代码适用于数据库的所有状态。升级到新版本的 DB 只会调用一次,因此onCreate只会在您第一次创建数据库时调用,然后再也不会调用!在开发过程中,这可能很烦人,因为您必须在每次测试运行之前删除整个数据库context.deleteDatabase(DATABASE_NAME)
于 2013-09-18T06:40:01.357 回答
1

在 onCreate 首先你必须像这样创建表:

  db.execSQL("CREATE TABLE "+DATABASE_TABLE + " (" +
                    KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    KEY_NAME + " TEXT NOT NULL, " +
                    KEY_HOTNESS + " TEXT NOT NULL);"
                    );

编辑:

public long createEntry(String name, String employeeCode, int mobileNum) {
    // TODO Auto-generated method stub
    ContentValues cv = new ContentValues();
    cv.put(NAME, name);
    cv.put(EMPLOYEE_CODE, employeeCode);
    cv.put(MOBILE_NUMBER, mobileNum);
    return db.insert("Employees", null, cv);
}

从 oncreate 调用此方法并传递您要插入的内容。

于 2013-09-18T06:33:51.947 回答
0

看看这个例子

public class RouteDbAdapter 
{

public static final String KEY_PLACE = "place";
public static final String KEY_LATITUDE = "latitude";
public static final String KEY_LONGITUDE = "longitude";
public static final String KEY_ROWID = "_id";

private static final String TAG = "RouteDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;


private static final String DATABASE_CREATE =
    "create table routes (_id integer primary key autoincrement, "
    + "place text not null, latitude real not null, longitude real not null);";

private static final String DATABASE_NAME = "cojDB";
private static final String DATABASE_TABLE = "routes";
private static final int DATABASE_VERSION = 2;

private final Context mCtx;

private static class DatabaseHelper extends SQLiteOpenHelper 
{

    DatabaseHelper(Context context) 
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) 
    {

        db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 
    {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS routes");
        onCreate(db);
    }
}


public RouteDbAdapter(Context ctx) 
{
    this.mCtx = ctx;
}

public RouteDbAdapter open() throws SQLException 
{
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return this;
}

public void close()
{
    mDbHelper.close();
}

public long createPlace(String place, Double lat,Double lng) 
{
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_PLACE, place);
    initialValues.put(KEY_LATITUDE, lat);
    initialValues.put(KEY_LONGITUDE, lng);

    return mDb.insert(DATABASE_TABLE, null, initialValues);
}

public boolean deletePlace(String place) 
{

    return mDb.delete(DATABASE_TABLE, KEY_PLACE + "='" + place+"'", null) > 0;
}


 public Cursor fetchAllPlace()
 {
    return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_LATITUDE,
            KEY_LONGITUDE,KEY_PLACE}, null, null, null, null, null);
 }


    public Cursor fetchPlace(String place) throws SQLException 
    {

    Cursor mCursor = 
        mDb.query(true, DATABASE_TABLE, new String[] {KEY_LATITUDE,KEY_LONGITUDE}, KEY_PLACE + "= '" +       place+"'", null,
                null, null, null, null);
    if (mCursor != null) 
    {
        mCursor.moveToFirst();
    }
    return mCursor;
 }
}
于 2013-09-18T07:29:24.927 回答
0

查看创建表查询。m 给你一个示例查询。

CREATE TABLE IF NOT EXISTS menus (menuname TEXT,screens TEXT,menuitem TEXT,menuposition TEXT,menuid TEXT,PRIMARY KEY(menuid));

并在插入前执行创建表查询。onCreate()在您的方法中添加上述代码。

于 2013-09-18T06:31:22.733 回答
0

您忘记创建 TABLE。您需要在 onUpgrade 表中的 OnCreate 或(可选)UPDATE 表中执行 DATABASE_CREATE 查询。请参阅以下代码,请参阅 UPDATED 和 ADDED 标签

.. SQLite 说,主键必须命名为 _id

public class DummyDatabase extends SQLiteOpenHelper {
public static final int NAME_COLUMN = 2;
static final String DATABASE_NAME = "NestDatabase.db";
static final int DATABASE_VERSION = 1;
static final String tableName = "Employees";
static final String DATABASE_CREATE = "CREATE TABLE employees (_id INTEGER PRIMARY KEY, name TEXT, mobile_number TEXT);"; /** UPDATED **/


public SQLiteDatabase db;
private final Context context;
public DataBaseHelper1 dbHelper;

public DummyDatabase(Context _context) {
    super(_context, DATABASE_NAME, null, DATABASE_VERSION);
    // TODO Auto-generated constructor stub
    context = _context;
    dbHelper = new DataBaseHelper1(_context, DATABASE_NAME,
            null, DATABASE_VERSION);
}


public DummyDatabase open() throws SQLException {
    db = dbHelper.getWritableDatabase();
    return this;
}

public void close() {
    db.close();
}

public int deleteEntry(String NAME) {
    String where = "NAME=?";
    int numberOFEntriesDeleted = db.delete("Employees", where, new String[]
            {NAME});
    Toast.makeText(context, "Number fo Entry Deleted Successfully : 
            "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show();
    return numberOFEntriesDeleted;

}

public String getEntry(String Emp_code) {
    Cursor cursor = db.query("Employees", null, " EMPLOYEE_CODE=?", new
            String[]{Emp_code}, null, null, null);
    if (cursor.getCount() < 1) // UserName Not Exist
    {
        return "NOT EXIST";
    }
    cursor.moveToFirst();
    String user = cursor.getString(cursor.getColumnIndex("NAME"));
    return user;
}


@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    db.execSQL(DATABASE_CREATE); //** ADDED */
    db.execSQL("insert into Employees( NAME , EMPLOYEE_CODE , MOBILE_NUMBER)
            "+"values('Alexander', 'A111', '1234567890'); ");
    db.execSQL("insert into Employees( NAME , EMPLOYEE_CODE , MOBILE_NUMBER) 
            "+"values('Bernie', 'B111', '1234567890'); ");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
}
}
于 2013-09-18T06:46:29.523 回答