android SQLite数据库封装

终于有时间好好看看数据库了

今天下午自己封装了一个SQLite数据库

留着以后自己用吧

虽然还有许多要修改的地方

贴出代码先

 

package com.example.testdatabase;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseManager {

 private DatabaseHelper dbHelper;
 private static final String tableName = "name_table";
 
 public DatabaseManager(Context context){
  
  dbHelper = new DatabaseHelper(context);
 }
 
 public SQLiteDatabase getReadDatabase(){
  
  return dbHelper.getReadableDatabase();
 }
 
 
 public void addData(String name, String num){
  SQLiteDatabase db = dbHelper.getWritableDatabase();
  
  ContentValues cv = new ContentValues();
  cv.put("name", name);
  cv.put("num", num);
  
  try{
   db.insertOrThrow(tableName, null, cv);
   db.close();
  }catch(Exception e){
   e.printStackTrace();
  }
  
 }
 
  public void deleteData(String strName){
  
  String sql = "delete from " + tableName + " where name = '"+ strName +"'" ;
  SQLiteDatabase db = dbHelper.getWritableDatabase();
  
  try{
   db.execSQL(sql);
//   db.delete(tableName, "name =  '" + strName + "' ", null);
  }catch(Exception e){
   e.printStackTrace();
  }
 }

 
 //查找指定数据
 public Cursor findData(String strNum){
  
  String sql = "select * from " + tableName + " where num = " + strNum;
  SQLiteDatabase db = dbHelper.getReadableDatabase();
  Cursor cursor = null;
  
  cursor = db.rawQuery(sql, new String[]{});
  
  return cursor;
 }
 
 //删除表
 public void deleteTable(){
  
  String sql = "drop table " + tableName;
  SQLiteDatabase db = dbHelper.getWritableDatabase();
  
  try{
   db.execSQL(sql);
  }catch(Exception e){
   e.printStackTrace();
  }
 }
 
 public Cursor viewData(){
  
  SQLiteDatabase db = dbHelper.getReadableDatabase();
  String sql = "select * from " + tableName;
  Cursor cursor = null;
  
  try{
   cursor = db.rawQuery(sql, new String[]{});
  }catch(Exception e){
   e.printStackTrace();
  }
  return cursor;
 }
 
 private class DatabaseHelper extends SQLiteOpenHelper{

  private static final String dbNameString = "database.db";
  private static final int db_version = 1;
  private static final String nameTableString = "create table " + tableName + "(" + "name VARCHAR(20)," + "num VARCHAR(20)" + ");";
  
  public DatabaseHelper(Context context) {
   super(context, dbNameString, null, db_version);
   
  }
  
  
  
  public void onCreate(SQLiteDatabase db) {
   db.execSQL(nameTableString);
   
  }
  
  @Override
  public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
   
  }
  
 }
}


//在外部类中调用如下
//如添加数据
DatabaseManager dm = null;
dm = new DatabaseManager(context);
dm.addData("张三", "123456");


本文出自 “爬过山见过海” 博客,转载请与作者联系!

你可能感兴趣的:(数据库,android,database)