欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android SQLite 博客分类: other android SQLiteandroid 数据库SQLiteOpenHelper 

程序员文章站 2024-02-09 11:36:10
...

 

1.编写DataBaseOpenHelper 继承SQLiteOpenHelper 

完成创建、打开数据库及各种数据库操作。

public class DataBaseOpenHelper extends SQLiteOpenHelper {

 

public DataBaseOpenHelper(Context context, String name,

CursorFactory factory, int version) {

super(context, name, factory, version);

}

 

 

@Override

public void onCreate(SQLiteDatabase db) {

db.execSQL("create table if not exists person("

+ "id integer primary key,"

+ "name varchar(20),"

+ "brith DateTime)");

db.execSQL("create table if not exists teacher("

+ "id integer primary key,"

+ "name varchar(20),"

+ "course varchar(20))");

}

 

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

 

}

 

}

 

2.TeacherDaoImpl  teacher表的数据库访问类 ,完成数据的相关操作。

 

package com.fullwisdom.sqllite.dao;

 

import android.content.ContentValues;

 

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

 

import com.fullwisdom.sqllite.DataBaseOpenHelper;

import com.fullwisdom.sqllite.beans.Teacher;

 

public class TeacherDaoImpl {

 

 

private DataBaseOpenHelper databaseHelper;

 

public TeacherDaoImpl(DataBaseOpenHelper databaseHelper){

this.databaseHelper = databaseHelper;

}

 

public long save(Teacher t){

SQLiteDatabase db =  databaseHelper.getWritableDatabase();

ContentValues values = new ContentValues();

values.put("name", t.getName());

values.put("course", t.getCourse());

long rowid = db.insert("teacher", null, values);

return rowid;

}

 

public Teacher find(int id){

SQLiteDatabase db = databaseHelper.getReadableDatabase();

Cursor cursor = db.query(true, "teacher", new String[]{"id","name","course"},"id=?",

new String[]{id+""}, null, null, null, null);

 

if(!cursor.moveToFirst()){

return null;

}

int pid = cursor.getInt(cursor.getColumnIndex("id"));

String pname = cursor.getString(cursor.getColumnIndex("name"));

Teacher t = new Teacher();

t.setId(pid);

t.setName(pname);

return t;

}

}

 
3.执行数据库操作
 
DataBaseOpenHelper dataBaseOpenHelper = new DataBaseOpenHelper(this, "liu.db", null, 1);
        PersonDaoImpl personDao = new PersonDaoImpl(dataBaseOpenHelper);
        
        Person p = new Person();
        p.setName("liuzhiquan");
        long id = personDao.save(p);
        
        System.out.println("id-----:"+id);
        
        Person p1 = personDao.find(1);
        
        System.out.println(p1);
        
        
        Teacher t = new Teacher();
        t.setName("wuhaibo");
        t.setCourse("computer");
        
        TeacherDaoImpl  teacherDao=  new TeacherDaoImpl(dataBaseOpenHelper);
        teacherDao.save(t);
        
        
        System.out.println(teacherDao.find(1));