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.example.Sqlutil.MySqliteOpenHelper; /** * studentinfo --> Student實體 --->StudentService 對Student實體的操做類(增刪改查) * student2.db: data/data/{包名}/database/xxx.db 面向對象的封裝操做類 */ public class StudentService { private MySqliteOpenHelper dbhelper; // 除了用execSQL()進行增刪改外,另外SqliteOpenHelper封裝了delete(),insert(),update()方法 // 面向對象的封裝操做類 public StudentService(Context context) { dbhelper = new MySqliteOpenHelper(context); } // 查找全部 public List<Student> findAllStudents() { List<Student> list = new ArrayList<Student>(); // dbHelper.getReadableDatabase() : 若是空間不足,不能寫,只能讀 // dbHelper.getWritableDatabase(); 若是空間不足,既不能寫,也不能讀(報錯) SQLiteDatabase db = dbhelper.getReadableDatabase(); Cursor cursor = db.rawQuery("select*from studentinfo", null); while (cursor.moveToNext()) { // 按如下方式寫時要注意數據庫順序 int sid = cursor.getInt(0); String sname = cursor.getString(1); String sex = cursor.getString(2); int score = cursor.getInt(3); Student stu = new Student(sid, sname, sex, score); list.add(stu); } cursor.close(); db.close(); return list; } // 添加 public long add(Student student) { SQLiteDatabase db = dbhelper.getReadableDatabase(); ContentValues values = new ContentValues(); values.put("sname", student.getSname()); values.put("sex", student.getSex()); values.put("score", student.getScore()); long row = db.insert("studentinfo", null, values); // 插入成功後返回的是影響的主鍵 db.close(); return row; } // 更新 public int update(ContentValues values, String whereClause, String[] whereArgs) { SQLiteDatabase db = dbhelper.getReadableDatabase(); int row = db.update("studentinfo", values, whereClause, whereArgs); db.close(); return row;// 返回的是受影響的行 } // 刪除 public int delete(String whereClause, String[] whereArgs) { SQLiteDatabase db = dbhelper.getReadableDatabase(); int row = db.delete("studentinfo", whereClause, whereArgs); db.close(); return row;// 返回的是受影響的行 } } //SQLiteOpenHelper類 public class MySqliteOpenHelper extends SQLiteOpenHelper { private static final String DBNAME = "student2.db"; private static final int VERSION = 1;// 版本能夠本身取 public MySqliteOpenHelper(Context context) { super(context, DBNAME, null, VERSION); } @Override public void onCreate(SQLiteDatabase db) { // 建立數據庫表,首次升級時調用,初始化一些數據 String sql = "create table studentinfo " + " (sid integer primary key autoincrement not null," + " sname varchar(30) not null," + " sex varchar(2) not null," + " score integer not null)"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // 大於舊版本時,就升級 if (newVersion > oldVersion) { db.execSQL("drop table if exists studentinfo "); // 實際操做是先備份數據,再進行刪除升級 } } }