数据库增删查

首先建一个类继承SQLiteOpenHelper重写里面的方法


package com.bw.uigaoji.sql;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class SQLiteHelper extends SQLiteOpenHelper {
    public SQLiteHelper(Context context) {
        super(context, "zhi.db", null, 1); // 第2个参数 数据库的名字,第3个参数用默认的CusorFactory,第3个参数数据库版本号
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        //创建名字为user的表主键自动增长aid,title,desc都是字符串类型
        String sql = "CREATE TABLE user(personid integer primary key autoincrement, aid varchar(20),title varchar(20),desc varchar(20)) ";
       //通过sql语句创建表
        db.execSQL(sql);
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }
}


实例化上边继承数据库那个类调用得到数据库


getWritableDatabase


  //实例化数据库类
  SQLiteHelper sql=new SQLiteHelper(getActivity());
  //得到数据库
  SQLiteDatabase writableDatabase = sql.getWritableDatabase();
  //把表里的数据全部删除
 writableDatabase.execSQL("delete from user");
  //循环添加数据
for (int i = 0; i <list2.size() ; i++) {
      User user = list2.get(i);
      writableDatabase.execSQL("insert into user(aid,title,desc) values(?,?,?)",
              new Object[]{user.getAid(), user.getTitle(), user.getDescription()});
  }
  //查询数据库里的所有数据放入user对象里在放入集合
  List users=new ArrayList<>();
  Cursor cursor = writableDatabase.rawQuery("select * from user", null);
  for (int i = 0; i ; i++) {
      cursor.moveToNext();
      User u=new User();
      u.setAid(cursor.getString(1));
      u.setTitle(cursor.getString(2));
      u.setDescription(cursor.getString(3));
      users.add(u);
  }

根据aid查询的数据放入对象里


Cursor cursor = writableDatabase.rawQuery("select * from user where aid=?",new String[]{s});
if (cursor.moveToNext()){
    u = new User();
    u.setAid(cursor.getString(1));
    u.setTitle(cursor.getString(2));
    u.setDescription(cursor.getString(3));

}


你可能感兴趣的:(数据库增删查)