向/从SQLite插入和检索数据

时间:2018-05-07 10:45:37

标签: android database sqlite android-sqlite

我是android中sqllite的新手。我正在向sql数据库添加记录,insert和select查询都没有给出运行时错误,除了我在获取数据时有空光标(在Select Query上)。如果在插入值或获取值时出现问题,请告诉我。与选择查询一样,我得到列名但没有记录。 这是我的代码。

public class SQLHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "MyDb.db";
private static final int DATABASE_VERSION = 1;
private SQLiteDatabase database;

public String stringArray[];
private ArrayList<tasksList> arrayList;

public final static String PROCESS_TABLE = "Process";
public final static String DB_P_ID = "db_process_id";
public final static String PROCESS_ASSIGNMENT_ID = "process_id";
public final static String CASETITLE = "case_title";
public final static String APPEARANCE_DATE = "appearance_date";
public final static String APPEARANCE_TIME = "appearance_time";
public final static String APPEARANCE_REASON = "appearance_reason"; 
public final static String COURT_NAME = "court_name";
public final static String RESPONDENT_NAME = "respondent_name";
public final static String ADDRESS = "address";
public final static String CONTACT_NO = "contact_no";
public final static String CNIC = "cnic";
public final static String NOTICE_NUMBER = "notice_number";

private static final String DATABASE_CREATE_PROCESS_TABLE = " CREATE TABLE "+ PROCESS_TABLE + " (db_process_id integer primary key autoincrement," +
        " process_id text not null," +
        " case_title text not null,appearanc e_date text not null ,appearance_time text not null, court_name text not null , respondent_name text not null ," +
        " address text not null ,contact_no text not null ,cnic text not null , appearance_reason text not null , notice_number text not null );";

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


@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    sqLiteDatabase.execSQL(DATABASE_CREATE_PROCESS_TABLE);
}

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

public Boolean insertProcess(String id, String case_Title,String app_date, String app_time, String app_reason,
                           String court_name,String name,String location,String cnic,String notice_no,String contact_no) {

    database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(PROCESS_ASSIGNMENT_ID, id);
    values.put(CASETITLE, case_Title);
    values.put(APPEARANCE_DATE, app_date);
    values.put(APPEARANCE_TIME, app_time);
    values.put(APPEARANCE_REASON, app_reason);
    values.put(COURT_NAME, court_name);
    values.put(RESPONDENT_NAME, name);
    values.put(ADDRESS, location);
    values.put(CONTACT_NO, contact_no);
    values.put(CNIC, cnic);
    values.put(NOTICE_NUMBER, notice_no);
    database.insert(PROCESS_TABLE, null, values);

    return true;

}

public Cursor getCompletedTask(Context applicationContext) {
    Context context = applicationContext;
    database = this.getReadableDatabase();
    String[] cols = new String[] { CASETITLE};

    Cursor mCursor = database.rawQuery(" Select * from " + PROCESS_TABLE , null);

 //        Cursor mCursor = database.query(true, PROCESS_TABLE, cols, null, null, null, null,  null, null);
    int size = mCursor.getCount();
    stringArray = new String[size];
    if (mCursor != null) {
        mCursor.moveToFirst();
        while (!mCursor.isAfterLast()) {
            String id = mCursor.getString(0);
            String title = mCursor.getString(1);

            tasksList fooditem=new tasksList();
            fooditem.setCase_id(id);
            fooditem.setCase_title(title);
            arrayList.add(fooditem);
            mCursor.moveToNext();
        }
    }
    return mCursor; // iterate to get each value.
}

2 个答案:

答案 0 :(得分:0)

您的问题是 appearanc e_date text not null 中有空格,即这应该是 appearance_date text not null

说这本身不会导致失败,只是列名称将是 appearanc 而不是appearance_date。这很可能会导致  随之而来的混淆(例如您可能发生的问题如下)。

这是为什么建议依赖单个源表和列名的一个主要示例。因此,而不是纠正: -

private static final String DATABASE_CREATE_PROCESS_TABLE = " CREATE TABLE "+ PROCESS_TABLE + " (db_process_id integer primary key autoincrement," +
        " process_id text not null," +
        " case_title text not null,appearance_date text not null ,appearance_time text not null, court_name text not null , respondent_name text not null ," +
        " address text not null ,contact_no text not null ,cnic text not null , appearance_reason text not null , notice_number text not null );";

我建议如下: -

private static final String CREATE_PROCESS_TABLE = 
        "CREATE TABLE IF NOT EXISTS " +
                PROCESS_TABLE + 
                "(" +
                PROCESS_ASSIGNMENT_ID + " INTEGER PRIMARY KEY," + //NOTE you very likely don't want autoincrement
                CASETITLE + " TEXT NOT NULL," +
                APPEARANCE_DATE + " TEXT NOT NULL," +
                APPEARANCE_TIME + " TEXT NOt NULL," +
                COURT_NAME + " TEXT NOT NULL, " +
                RESPONDENT_NAME + " TEXT NOT NULL," +
                ADDRESS + " TEXT NOT NULL," +
                CONTACT_NO + " TEXT NOT NULL, " +
                CNIC + " TEXT NOT NULL," +
                APPEARANCE_REASON + " TEXT NOT NULL," +
                NOTICE_NUMBER + " TEXT NOT NULL" +
                ")";

您的问题可能是由于非预期的列名称 appearan 而非预期的 appearance_date 列名称导致的插入记录不会知道列 appearance_date 而不插入行。所以你的桌子将是空的。

如果您查看日志,您会看到类似于: -

的内容
05-07 21:13:54.724 1285-1285/? E/SQLiteLog: (1) table Process has no column named appearance_date

如上所述进行更正(删除不需要的空间),删除应用程序的数据,然后重新运行应用程序应该纠正该问题。

答案 1 :(得分:-2)

为插入数据和反向数据制作模型类..

试试这段代码..

public class DBHelper extends SQLiteOpenHelper{

//USER TABLE
public static final String USER_TABLE_NAME = "MyTableTwo";
public static final String USER_COLUMN_USER_ID = "id";
public static final String USER_COLUMN_USER_NAME = "Item_Name";
public static final String USER_COLUMN_USER_ADDRESS = "Weight";
public static final String USER_COLUMN_USER_CREATED_AT = "MRP";
public static final String USER_COLUMN_USER_UPDATED_AT = "BARCODE";

public DBHelper(Context context,
                String dbName,
                Integer version) {
    super(context, dbName, null, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
    tableCreateStatements(db);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + USER_TABLE_NAME);
    onCreate(db);
}

private void tableCreateStatements(SQLiteDatabase db) {
    try {
        db.execSQL(
                "CREATE TABLE IF NOT EXISTS "
                        + USER_TABLE_NAME + "("
                        + USER_COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                        + USER_COLUMN_USER_NAME + " VARCHAR(20), "
                        + USER_COLUMN_USER_ADDRESS + " VARCHAR(50), "
                        + USER_COLUMN_USER_CREATED_AT + " VARCHAR(10) DEFAULT " + getCurrentTimeStamp() + ", "
                        + USER_COLUMN_USER_UPDATED_AT + " VARCHAR(10) DEFAULT " + getCurrentTimeStamp() + ")"
        );

    } catch (SQLException e) {
        e.printStackTrace();
    }
}
public List<MyTableTwo> getMyItems() {
    List<MyTableTwo> mySuperList = new ArrayList<>();
    SQLiteDatabase db = this.getReadableDatabase();
    String selectQuery = "SELECT  * FROM " + USER_TABLE_NAME ;
    Cursor c = db.rawQuery(selectQuery, null);
    if (c != null) {
        c.moveToFirst();
        while (c.isAfterLast() == false) {
            MyTableTwo myTable = new MyTableTwo();
            myTable.itemName = (c.getString(c.getColumnIndex("Item_Name")));
            myTable.weight = (c.getString(c.getColumnIndex("Weight")));
            myTable.mrp = (c.getString(c.getColumnIndex("MRP")));
            myTable.barcod = (c.getString(c.getColumnIndex("BARCODE")));

            mySuperList.add(myTable);
            c.moveToNext();
        }
    }
    return mySuperList;
}

public Long insertUser(MyTableTwo user) throws Exception {
    try {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(USER_COLUMN_USER_NAME, user.itemName);
        contentValues.put(USER_COLUMN_USER_ADDRESS, user.barcod);
        contentValues.put(USER_COLUMN_USER_CREATED_AT, user.weight);
        contentValues.put(USER_COLUMN_USER_UPDATED_AT, user.barcod);

        return db.insert(USER_TABLE_NAME, null, contentValues);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

private String getCurrentTimeStamp() {
    return String.valueOf(System.currentTimeMillis() / 1000);
}

}

和actvity使用如下。

DBHelper dbHelper=new DBHelper(DbInsert.this,"DB",1);
            MyTableTwo myTableTwo=new MyTableTwo("abcd","5kg","120","xyz");
            try {
                dbHelper.insertUser(myTableTwo);
            } catch (Exception e) {
                e.printStackTrace();
            }

pojo class ..

public class MyTableTwo {

public String itemName,weight,mrp,barcod;
public MyTableTwo(){}
public MyTableTwo(String itemName, String weight, String mrp, String barcod) {
    this.itemName = itemName;
    this.weight = weight;
    this.mrp = mrp;
    this.barcod = barcod;
}

}

你也做了getter setter方法..