Android SQLite数据库增删改查操作代码示例及错误分析
Android SQLite数据库增删改查操作代码示例及错误分析
在Android开发中,使用SQLite数据库进行数据存储是常见的做法。本文将提供一个完整的SQLite数据库增删改查操作代码示例,并分析其中 updateNote 方法存在的错误以及解决方案,帮助你更好地理解和使用SQLite数据库。
代码示例
以下是一个名为 ZSGC 的类的代码,它封装了对SQLite数据库进行增删改查的操作:javapublic class ZSGC { SQLiteOpenHelper dbHandler; SQLiteDatabase db;
private static final String[] columns = { NoteDatabase.ID, NoteDatabase.CONTENT, NoteDatabase.TIME, NoteDatabase.MODE };
public ZSGC(Context context){ dbHandler=new NoteDatabase(context); }
public void open(){ db=dbHandler.getWritableDatabase(); } public void close(){ dbHandler.close(); }
//把note 加入到database里面 public Note addNote(Note note){ //add a note object to datebase ContentValues contentValues =new ContentValues(); contentValues.put(NoteDatabase.CONTENT,note.getContent()); contentValues.put(NoteDatabase.TIME,note.getTime()); contentValues.put(NoteDatabase.MODE,note.getTag()); long insertId =db.insert(NoteDatabase.TABLE_NAME,null,contentValues); note.setId(insertId); return note; }
public Note getNote(long id){ //get a note from database using cursor index Cursor cursor = db.query(NoteDatabase.TABLE_NAME,columns,NoteDatabase.ID+'=?', new String[]{String.valueOf(id)},null,null,null,null); if(cursor!=null) cursor.moveToFirst(); Note e =new Note(cursor.getString(1),cursor.getString(2),cursor.getInt(3)); return e; }
@SuppressLint('Range') public List<Note>getAllNotes(){ Cursor cursor=db.query(NoteDatabase.TABLE_NAME,columns,null,null,null,null,null);
List<Note> notes =new ArrayList<>(); if(cursor.getCount()>0){ while (cursor.moveToNext()){ Note note =new Note(); note.setId(cursor.getLong(cursor.getColumnIndex(NoteDatabase.ID))); note.setContent(cursor.getString(cursor.getColumnIndex(NoteDatabase.CONTENT))); note.setTime(cursor.getString(cursor.getColumnIndex(NoteDatabase.TIME))); note.setTag(cursor.getInt(cursor.getColumnIndex(NoteDatabase.MODE))); notes.add(note); } } return notes; }
public int updateNote(Note note){ //update the info of an existing note ContentValues values =new ContentValues(); values.put(NoteDatabase.CONTENT,note.getContent()); values.put(NoteDatabase.TIME,note.getTime()); values.put(NoteDatabase.MODE,note.getTag()); //updating row return db.update(NoteDatabase.TABLE_NAME,values, NoteDatabase.ID + ' = ' , new String[]{String.valueOf(note.getId())}); }
public void removeNote(Note note){ //remove a note according to ID value db.delete(NoteDatabase.TABLE_NAME,NoteDatabase.ID + ' = ' + note.getId(),null);
原文地址: https://www.cveoy.top/t/topic/ca7E 著作权归作者所有。请勿转载和采集!