android数据库操作

package com.tcl.kang;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper
{
private static final String NAME = "mydatabase";
private static final String TABLE_NAME = "tb_test";
private static final int VERSION = 1;
private String TABLE_NUM="_num";
private String TABLE_DATA="_data";
public DatabaseHelper(Context context)
{
super(context, NAME, null, VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
String sql = "CREATE TABLE "
+ TABLE_NAME
+ "(_id INTEGER PRIMARY KEY AUTOINCREMENT,_num text,_data text)";
db.execSQL(sql);// 需要异常捕获
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
String sql = "drop table " + "tb_test";
db.execSQL(sql);
onCreate(db);

}
/**
* 添加数据
*/
public long insert(String num, String data)
{
SQLiteDatabase db = getWritableDatabase();// 获取可写SQLiteDatabase对象
// ContentValues类似map,存入的是键值对
ContentValues contentValues = new ContentValues();
contentValues.put(TABLE_NUM, num);
contentValues.put(TABLE_DATA, data);
return db.insert(TABLE_NAME, null, contentValues);
}
/**
* /** 删除记录
*
* @param _id
*/
public void delete(String id)
{
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_NAME, "_id=?", new String[] { id });
}
  /**
     * 更新记录的,跟插入的很像
     */
    public void update(String _id,String num, String data){
            SQLiteDatabase db= getWritableDatabase();
                    ContentValues contentValues = new ContentValues();
                    contentValues.put(TABLE_NUM, num);
                    contentValues.put("TABLE_DATA", data);
                 db.update(TABLE_NAME, contentValues,
                    "_id=?",
                    new String[]{_id});
    }
    /**
     * 查询所有数据
     * @return Cursor
     */
    public Cursor select(){
            SQLiteDatabase db = getReadableDatabase();
                    return db.query(
                            TABLE_NAME,
                            new String[]{"_id",TABLE_NUM,TABLE_DATA},
                            null,
                            null, null, null, "_id desc"); //desc 降序排列,asc 升序排列
    }
}

你可能感兴趣的:(android)