美文网首页
android 数据库的操作

android 数据库的操作

作者: 好大一只鹏 | 来源:发表于2016-08-19 22:11 被阅读0次

一.Sqlite在安卓中应用广泛,主要存储一些数据,我们可以对他进行增删查改等操作。

  • 什么是Sqlite数据库?
    这个应用程序允许你浏览Android上SQLite数据库。你可以选择从以下三种方法打开数据库。1.打开数据库文件直接。2.发送一个意图和内容提供商的uri。3.发送一个意图和数据库文件的完整路径。
  • 应用设计
    SQLite是一个嵌入式库并且实现了零配置、无服务端和事务功能的SQL数据库引擎。它在广泛领域内被使用,而且单线程读写性能与MySQL比肩,并且保证ACID性。
    SQLite的存储后端是采用Btree实现,多个连接可以并发操作,但是同一时间只允许一个写着存在。
    SQLite在硬盘上一个数据库一个文件,每个数据库文件头部保存有这个数据库的元信息,包括版本,大小,Btree根节点位置等等。
  • 特色
    轻量级;独立;隔离;跨平台;多语言接口;安全性。
  • 如何创造数据库呢
public class DatabaseHelp extends SQLiteOpenHelper{  
  public DatabaseHelp(Context context) { 

       super(context, "test.db", null, 1);  
  }   
 @Override   
 public void onCreate(SQLiteDatabase db) {  
      db.execSQL("create table user(username varchar(11) not null,password varchar(20) not null);");       //使用数据库的语言创造了一个user的表,里面有username和password两个字段
  }   
 @Override  
 public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {               //用于升级数据库
  }
}

SQLiteOpenHelp是系统帮助打开的方法;

接下来就是add 数据啦,
新建一个类-DatabaseActivity
添加数据:

DatabaseHelp databaseHelp=new DatabaseHelp(this);
mSQLiteDatabase=databaseHelp.getWritableDatabase();
//add data     IO操作,建议后台
ContentValues contentValues=new ContentValues();
contentValues.put("username","1234567");//用contentValue.put加入数据
contentValues.put("password","qq1234567");    //
mSQLiteDatabase.insert("user",null,contentValues);   

然后是查询数据:

Cursor cursor = mSQLiteDatabase.query("user", null, null, null, null, null, null);
if (cursor.moveToFirst()) { 
   int count = cursor.getCount();   
 for (int i = 0; i < count; i++) {    
    String username = cursor.getString(cursor.getColumnIndexOrThrow("username"));      //取得表中username 的数据
       String password = cursor.getString(cursor.getColumnIndexOrThrow("password"));    //   取得password的数据
        Toast.makeText(MainActivity.this,"帐号是"+username+"密码是"+password,Toast.LENGTH_LONG).show();     //使用Toast打印数据
   }  
 }

删除数据:

// delete:
String whereClauseString = "username=?";
String[] whereArgsString = {"   "};
mSqLiteDatabase.delete("user", whereClauseString, whereArgsString);

增添数据update:

// update
ContentValues contentValues = new ContentValues();
contentValues.put("password", "10000000000000");
String whereClauseString = "username=?";
String[] whereArgsString = {"自己的数据"};
mSqLiteDatabase.update("uesr",contentValues, whereClauseString, whereArgsString);

二. Content Provider

  • 应用程序间数据的共享
  • 为存储和获取数据提供了统一的接口
  • android为一些数据提供了默认的Content Provider
  • 四大组件之一
    来自geogle的定义:
  • 内容提供者将一些特定的应用程序数据提供给其他应用程序使用
  • 数据可以用于存储件系统,SQLite数据库或其他方式
  • 内容提供者继承于Content Provider基类,为其他应用程序取用和存储管理他的方法作为替代
  • 应用程序并不是直接调用这些方法,而是使用ContentResolver对象,调用他的方法作为替代
  • ContentResolver可以与任意内容提供者进行会话,与其合作来对所有相关交互通讯进行管理

相关文章

网友评论

      本文标题:android 数据库的操作

      本文链接:https://www.haomeiwen.com/subject/nubbsttx.html