資料儲存-SQLiteOpenHelper(SQLite資料庫增刪改查)
阿新 • • 發佈:2019-02-15
一、Android資料儲存方式
•1.檔案 •2.SQLite資料庫 •3.SharedPreferences(引數) •4.內容提供者(Content Providers) •5.網路二、SQLiteOpenHelper的使用方法
—SQLiteOpenHelper是一個訪問SQLite的助手類。 —編寫繼承SQLiteOpenHelper的類,此類提供方法:1、呼叫SQLiteOpenHelper的getReadableDatabase或getWriteableDatabase兩個方法獲得可讀、可寫的SQLiteOpenHelper物件。New一個物件時不會建立資料庫物件,只有呼叫這兩個方法中的任意一個後,才會建立資料庫物件。
2、回撥函式
onCreate:該函式會在第一次建立資料庫的時候執行,一般可用於建立表。
onUpgrade:該函式在資料庫版本發生改變時被呼叫,一般可用於修改表結構。
三、SQLiteOpenHelper的onUpgrade方法
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { // 把原有表格備份 arg0.execSQL("alter table salaryInfo rename to temp_salaryInfo"); // 建立新的表格 arg0.execSQL("create table salaryInfo (_id integer primary key autoincrement, name varchar(10), company varchar(20), salary integer)"); // 把原表格資料插入到新表格中 arg0.execSQL("insert into salaryInfo (sname, sage, sex) select sname,sage,'女' from temp_salaryInfo"); }
或者直接修改表結構
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("alter table salaryInfo add phone varchar(12) null");
}
四、使用事務
//------------------------------------------------------------------- //使用事務-模擬銀行轉賬 public void payment(){ SQLiteDatabase db = helper.getWritableDatabase(); db.beginTransaction();//開啟事務 try{ db.execSQL("update salaryInfo set salary=salary-10 where _id=1"); db.execSQL("update salaryInfo set salary=salary+10 where _id=2"); //事務的標誌決定事務結束時的狀態,若標誌為true事務就會commit,反之則rollback,預設情況下標誌為false db.setTransactionSuccessful();//設定事務的標誌為true }finally{ db.endTransaction();//結束事務,有兩種情況:commit、rollback } }
五、檔案事例
SalaryInfoDBOpenHelper.java檔案
package com.itheima.salary.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
/**
* 建立一個數據庫開啟的幫助類 實現預設的構造方法指定資料庫的名稱 遊標工廠 資料庫的版本
* 在oncreate()方法裡面初始化資料庫的表結構
* @author Administrator
*
*/
public class SalaryInfoDBOpenHelper extends SQLiteOpenHelper {
//實現一個預設的構造方法
public SalaryInfoDBOpenHelper(Context context) {
super(context, "student.db", null, 1);
}
//資料庫第一次被建立的時候呼叫的方法,適合做資料庫表結構的初始化
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table salaryInfo (_id integer primary key autoincrement, name varchar(10), company varchar(20), salary integer)");
}
//資料庫版本號變更時會呼叫onUpgrade方法,適合軟體更新
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("alter table salaryInfo add phone varchar(12) null");
}
}
Student.java檔案
package com.itheima.salary.domain;
public class Student {
private int id;
private String name;
private String company;
private int salary;
public Student(){}
public Student(int id, String name, String company, int salary){
this.id = id;
this.name = name;
this.company = company;
this.salary = salary;
}
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 String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
@Override
public String toString() {
return "StudentInfo [id=" + id + ", name=" + name + ", company="
+ company + ", salary=" + salary + "]";
}
}
StudentDao.java檔案
package com.itheima.salary.db.dao;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.itheima.salary.db.SalaryInfoDBOpenHelper;
import com.itheima.salary.domain.Student;
/**
* 學生資訊 操作訪問的dao 處理學生資料的增刪改查
*
*/
public class StudentDao {
private Context context;
private SalaryInfoDBOpenHelper helper;//繼承自SQLiteOpenHelper的類
/**
* 在構造方法裡面必須傳遞進來一個上下文物件
* @param context
*/
public StudentDao(Context context) {
this.context = context;
// 構造方法例項化資料庫開啟的幫助類
helper = new SalaryInfoDBOpenHelper(context);
}
//-------------------------------------------------------------------
//使用execSQL和rawQuery對資料庫進行增刪改查
/**
* 向學生資料庫插入一條記錄
* @param name 學生姓名
* @param company 公司名稱
* @param salary 學生的工資
*/
public void insert(String name, String company, int salary) {
SQLiteDatabase db = helper.getWritableDatabase();
//execSQL方法可以執行sql的語句,但不可以執行查詢語句;第二個引數bindArgs是對應語句中佔位符的值,數值採用佔位符?,避免參數有li'ming的情況出現
db.execSQL(
"insert into salaryInfo (name,company,salary) values (?,?,?)",
new Object[] { name, company, salary });
// 節約資源。關閉資料庫
db.close();
}
/**
* 根據學生的id刪除資料
* @param id 學生的id號碼
*/
public void delete(int id) {
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("delete from salaryInfo where _id=?", new Object[] { id });
db.close();
}
/**
* 刪除多個學生
* @param sids
*/
public void del(Integer... sids){
SQLiteDatabase db = helper.getWritableDatabase();
if(sids.length > 0){
StringBuffer sb = new StringBuffer();
for(int i = 0; i < sids.length; i++){
sb.append('?').append(',');//新增多個佔位符
}
sb.deleteCharAt(sb.length() - 1);//刪除最後多餘的一個” ,”
db = helper.getWritableDatabase();
String sql = "delete from salaryInfo where sid in ("+sb+")";
db.execSQL(sql, (Object[])sids);//刪除多個sid
}
db.close();
}
/**
* 更新學員的薪水資訊
* @param id 學生的id
* @param newsalary 新的工資資訊
*/
public void updateSalary(int id, int newsalary) {
SQLiteDatabase db = helper.getWritableDatabase();
db.execSQL("update salaryInfo set salary=? where _id=?", new Object[] {
newsalary, id });
db.close();
}
/**
* 根據學生是的id查詢學生的資訊。
* @param id
* @return 學生資訊的物件。 如果返回null代表是沒有查詢到當前學生
*/
public Student find(int id){
//獲取到一個可讀的資料庫
SQLiteDatabase db = helper.getReadableDatabase();
//執行查詢語句,查詢結果放入結果集的遊標cursor中
Cursor cursor = db.rawQuery("select * from salaryInfo where _id=?",
new String[]{String.valueOf(id)});
Student student = null;
//第一次使用moveToNext方法,使cursor指向查詢結果中的第一條記錄
if(cursor.moveToNext()){
String name = cursor.getString(cursor.getColumnIndex("name"));
String company = cursor.getString(cursor.getColumnIndex("company"));
int salary = cursor.getInt(cursor.getColumnIndex("salary"));
student = new Student(id, name, company, salary);
}
cursor.close();
db.close();
return student;
}
/**
* 分頁獲取記錄
* @param offset 跳過多少條記錄
* @param maxresult 獲取多少條記錄
* @return
*/
public List<Student> getScrollData(int offset, int maxresult){
List<Student> students = new ArrayList<Student>();
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from salaryInfo group by_id asc limit ?,?",
new String[]{String.valueOf(offset), String.valueOf(maxresult)});
while(cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex("id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String company = cursor.getString(cursor.getColumnIndex("company"));
int salary = cursor.getInt(cursor.getColumnIndex("salary"));
Student student = new Student(id, name, company, salary);
students.add(student);
}
db.close();
return students;
}
public long getCount(){
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select count(*) from salaryInfo", null);
cursor.moveToFirst();
long count = cursor.getLong(0);
return count;
}
//-------------------------------------------------------------------
//使用insert、update、query、delete對資料庫進行增刪改查
public void add1(Student student){
SQLiteDatabase db = helper.getWritableDatabase();
db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("_id", student.getId());
values.put("name", student.getName());
values.put("company", student.getCompany());
values.put("salary", student.getSalary());
db.insert("salaryInfo", "_id", values);
}
public void update1(Student student){
SQLiteDatabase db = helper.getWritableDatabase();
db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("_id", student.getId());
values.put("name", student.getName());
values.put("company", student.getCompany());
values.put("salary", student.getSalary());
db.update("salaryInfo", values, "_id=?", new String[]{String.valueOf(student.getId())});
}
public Student find1(int sid){
SQLiteDatabase db = helper.getReadableDatabase();
Student student = null;
db = helper.getWritableDatabase();
Cursor cursor = db.query("salaryInfo",
new String[]{"_id","name","company","salary"}, "_id=?", new String[]{String.valueOf(sid)}, null,null,null);
if(cursor.moveToNext()){
student = new Student(cursor.getInt(cursor.getColumnIndex("_id")),
cursor.getString(cursor.getColumnIndex("name")),
cursor.getString(cursor.getColumnIndex("company")),
cursor.getInt(cursor.getColumnIndex("salary")));
}
return student;
}
public void del1(Integer... sids){
SQLiteDatabase db = helper.getWritableDatabase();
if(sids.length > 0){
StringBuffer sb = new StringBuffer();
String[] strSb = new String[sids.length];
for(int i=0; i<sids.length; i++){
sb.append('?').append(',');
strSb[i] = String.valueOf(sids[i]);
}
sb.deleteCharAt(sb.length()-1);
db.delete("salaryInfo", "_id in ("+sb+")", strSb);
}
}
public List<Student> getScrollData1(int start, int count){
SQLiteDatabase db = helper.getReadableDatabase();
List<Student> students = new ArrayList<Student>();
db = helper.getWritableDatabase();
String sql = "select _id,name,company,salary from salaryInfo limit ?,?";
String[] selectionArgs = new String[]{start+"", count+""};
Cursor cursor = db.query("salaryInfo", new String[]{"_id","name","company","salary"}, null, null, null, null, "_id desc", start+","+count);
while(cursor.moveToNext()){
students.add(new Student(cursor.getInt(cursor.getColumnIndex("_id")),
cursor.getString(cursor.getColumnIndex("name")),
cursor.getString(cursor.getColumnIndex("company")),
cursor.getInt(cursor.getColumnIndex("salary"))));
}
return students;
}
public long getCount1(){
SQLiteDatabase db = helper.getWritableDatabase();
String sql = "select count(sid) from salaryInfo";
Cursor cursor = db.query("salaryInfo", new String[]{"count(*)"}, null,null,null,null,null);
if(cursor.moveToNext()){
return cursor.getLong(0);
}
return 0;
}
}
MainActivity.java檔案
package com.itheima.salary;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import com.itheima.salary.db.dao.StudentDao;
import com.itheima.salary.domain.Student;
public class MainActivity extends Activity {
private StudentDao dao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dao = new StudentDao(this);
}
/**
* 新增一條記錄的按鈕
* @param view
*/
public void add(View view){
dao.insert("張三", "xx科技公司", 1000);
}
/**
* 刪除一條記錄
* @param view
*/
public void delete(View view){
dao.delete(1);
}
/**
* 更新學生工資資訊
* @param view
*/
public void update(View view){
dao.updateSalary(1, 9999);
}
/**
* 查詢某個學生的資訊
*/
public void query(View view){
Student info = dao.find(1);
System.out.println("學生的資訊:"+info.toString());
}
}
activity_main.xml檔案
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:onClick="add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="新增一條記錄" />
<Button
android:onClick="delete"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="刪除一條記錄" />
<Button
android:onClick="update"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="修改一條記錄" />
<Button
android:onClick="query"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="查詢一條記錄" />
</LinearLayout>