sqlite数据库基本操作

第一步

 package db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataBaseHelper extends SQLiteOpenHelper {
 public final static String DBBase_Name = "Local";// ----数据库名称
 public final static int DataBase_Version = 1;
 public DataBaseHelper(Context context) {
  super(context, DBBase_Name, null, DataBase_Version);
 }
 @Override
 // 创建 数据库表
 public void onCreate(SQLiteDatabase myDB) {
  try {
   String strSql = "CREATE TABLE [image] (" 
          + "[id] INTEGER  NOT NULL PRIMARY KEY,"
          + "[image] BLOB)";
   myDB.execSQL(strSql);
  } catch (Exception e) {
  }
 }
 @Override
 public void onUpgrade(SQLiteDatabase myDB, int oldVersion, int newVersion) {
  String strSql = "";
  switch (oldVersion) {
  case 2:
   try {
   } catch (Exception e) {
    // TODO: handle exception
   }
   break;
  default:
   break;
  }
 }
}

第二步

 package db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
public class BaseDao {
 public static SQLiteDatabase gRSqliteDB = null;
 public static SQLiteDatabase gWSqliteDB = null;
 // -----获取可读写数据库
 public static boolean getDataBase(Context context) {
  try {
   DataBaseHelper dbHelper = new DataBaseHelper(context);
   if (gRSqliteDB == null) {
    gRSqliteDB = dbHelper.getReadableDatabase();
   }
   if (gWSqliteDB == null) {
    gWSqliteDB = dbHelper.getWritableDatabase();
   }
  } catch (Exception e) {
   return false;
  }
  return true;
 }
 // ----数据库关闭
 public static void CloseDataBase() {
  if (gWSqliteDB != null) {
   gWSqliteDB.close();
  }
  if (gRSqliteDB != null) {
   gRSqliteDB.close();
  }
 }
}

第三步

 BaseDao.getDataBase(context);
boolean b = insertTable(string);
 // 插入字符串语句
 public boolean insertTable(String string) {
  Boolean bRet = false;
  try {
   ContentValues contentValues = new ContentValues();
   contentValues.put("id", 1);
   contentValues.put("image", string);
   long iRet = baseDao.gWSqliteDB.insert("image", null, contentValues);
   bRet = iRet > 0;
  } catch (Exception e) {
   e.getMessage();
  }
  return bRet;
 }
 // 查询语句
 public String selectTable(String id) {
  String s = null;
  String sql = "select image from image where id ='" + id + "'";
  try {
   Cursor cursor = baseDao.gRSqliteDB.rawQuery(sql, null);
   while (cursor.moveToNext()) {
    s = cursor.getString(cursor.getColumnIndex("image"));
   }
   cursor.close();
  } catch (Exception e) {
  }
  return s;
 }

转载于:https://my.oschina.net/u/2311668/blog/667988

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值