Sqlite的使用詳解
阿新 • • 發佈:2019-01-04
1.SQLite的介紹
sqlite是一款輕量型的資料庫,不需要安裝且不依賴第三方軟體,除了主流作業系統 windows,linux之後,SQLite還支援其它一些不常用的操作系 統。 當然sqlite也是Android原生資料庫,既然sqlite這麼好,那麼今天我就帶著大家一起探索一下sqlite的真面目。
2.SQLite的使用步驟
1.建立SQLiteDBHelper, 繼承SQLiteOpenHelperclass SQLiteDBHelper extends SQLiteOpenHelper{ private static final int VERSION2.例項化SQLiteDataBase= 1; private static final String DB_NAME = "persons.db"; public SQLiteDBHelper(Context context) { //在構造器中建立資料庫 super(context,DB_NAME,null,VERSION); } @Override public void onCreate(SQLiteDatabase sqlitedatabase) { //在oncreate中建立表 sqlitedatabase.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY,name TEXT,age INTEGER)"); } @Override public void onUpgrade(SQLiteDatabase sqlitedatabase, int i, int j) { //修改表,建立新表,資料備份,刪除表 sqlitedatabase.execSQL("ALTER TABLE " + TABLE_NAME + " RENAME TO PERSON_TEMP"); sqlitedatabase.execSQL("CREATE TABLE "+ TABLE_NAME + " (_id integer primary key,name varchar(20),age integer,sex varchar(2))"); sqlitedatabase.execSQL("INSERT INTO " + TABLE_NAME + " (_id,name,age,sex) SELECT _id,name,age,'女' FROM PERSON_TEMP"); } }
//在類的構造方法中初始化Context,SQLiteDatabase public SQLiteDAO(Context cxt) { mContext = cxt; sqliteDBHelper = new SQLiteDBHelper(mContext); //建立資料庫 sqliteDataBase = sqliteDBHelper.getWritableDatabase(); }3.建立bean物件,併為之序列化
public class Person implements java.io.Serializable{ private static final long serialVersionUID = 1L; private int id; private String name; private int age; public Person(){} public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }以上表,庫建立完成,接著看具體操作:
3.SQLite的具體應用
1.增加資料://新增資料 public void insertPerson(Person person) { String INSERT_SQL = "INSERT INTO " + TABLE_NAME + " (" + COLUMN_NAME + "," + COLUMN_AGE + ") " + "VALUES (" + "'" + person.getName() + "'" + "," + person.getAge() + ")"; sqliteDataBase.execSQL(INSERT_SQL);如果你覺得麻煩的話,還可以:
ContentValues cv = new ContentValues(); cv.put(COLUMN_NAME, person.getName()); cv.put(COLUMN_AGE, person.getAge()); //當cv引數為空或者沒有內容的時候,insert會失敗,為了防止這種情況發生, // 要在第二個引數設定一個列名,當要插入的行為空行時,將指定的列名值設定為null sqliteDataBase.insert(TABLE_NAME, null, cv);2.刪除資料:
//刪除資料 public void deletePerson(int id) { String DELETE_SQL = "DELETE FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + " = " + id; sqliteDataBase.execSQL(DELETE_SQL);}同樣你也可以:
sqliteDataBase.delete(TABLE_NAME, COLUMN_ID + "=?", new String[]{String.valueOf(id)});3.修改資料:
//修改資料 public void updatePerson(Person person) { String UPDATE_SQL = "UPDATE " + TABLE_NAME + " SET " + COLUMN_NAME + " = " + "'" + person.getName() + "'" + " WHERE " + COLUMN_ID + " = " + person.getId(); sqliteDataBase.execSQL(UPDATE_SQL); }或者:
ContentValues cv = new ContentValues(); cv.put(COLUMN_NAME, person.getName()); sqliteDataBase.update(TABLE_NAME, cv, COLUMN_ID + "=?", new String[]{String.valueOf(person.getId())});4.查詢單條資料:
//查詢單條資料 public ArrayList<Person> findPerson(int sid) { ArrayList<Person> personList = new ArrayList<Person>(); Person person = new Person(); Cursor cursor = sqliteDataBase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + " = ?", new String[] { String .valueOf(sid) }); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex(COLUMN_ID)); String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME)); int age = cursor.getInt(cursor.getColumnIndex(COLUMN_AGE)); person.setId(id); person.setName(name); person.setAge(age); personList.add(person); } cursor.close(); return personList; }5.查詢所有資料:
//查詢所有資料 public ArrayList<Person> listPerson() { ArrayList<Person> personList = new ArrayList<Person>(); Cursor cursor = sqliteDataBase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " + COLUMN_ID + " IS NOT ?", new String[] { "NULL" }); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex(COLUMN_ID)); String name = cursor.getString(cursor.getColumnIndex(COLUMN_NAME)); int age = cursor.getInt(cursor.getColumnIndex(COLUMN_AGE)); Person person = new Person(); person.setId(id); person.setName(name); person.setAge(age); personList.add(person); } cursor.close(); return personList; }6.附上測試程式碼:
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //開啟或建立sqlite.db資料庫 SQLiteDatabase db = openOrCreateDatabase("sqlite.db",MODE_PRIVATE,null); db.execSQL("DROP TABLE IF EXISTS student"); //建立學生表 db.execSQL("CREATE TABLE student (_id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR , age SMALLINT)");Student student = new Student(); student.setName("xiaoxing"); student.setAge(23); //插入資料 db.execSQL("INSERT INTO student values(null,?,?)",new Object[]{student.getName(),student.getAge()}); student.setName("wangxiaoer"); student.setAge(24); //ContentValues以鍵值對的形式存放資料 ContentValues cv = new ContentValues(); cv.put("name",student.getName()); cv.put("age",student.getAge()); //插入contentValue的資料 db.insert("student",null,cv); //修改資料 cv = new ContentValues(); cv.put("age",30); db.update("student",cv,"name = ?",new String[]{"xiaoming"}); //查詢資料 Cursor c = db.rawQuery("SELECT * FROM student WHERE age > ?",new String[]{"20"}); while(c.moveToNext()){ int _id = c.getInt(c.getColumnIndex("_id")); String name = c.getString(c.getColumnIndex("name")); int age = c.getInt(c.getColumnIndex("age")); Log.i("db","_d=>"+_id+",name=>"+name+",age=>"+age); } c.close(); db.delete("student","name=?",new String[]{"wangxiaoer"});db.close();} }執行完成後,系統會預設在你的模擬器/data/data的目錄下生成你對應的資料庫,效果圖:
好了,今天就到這裡了,我是張星,歡迎您的關注,後期更精彩。