1 package com.hex.demosqlite;
2
3 import android.content.Context;
4 android.database.sqlite.SQLiteDatabase;
5 android.database.sqlite.SQLiteOpenHelper;
6
7 /**
8 * Created by Administrator on 2019/4/4.
9 */
10 public class DatabaseHelper extends SQLiteOpenHelper {
11
12 private static final String DB_NAME="persons.db";
13
14 final int DB_VERSION=115
16 public DatabaseHelper(Context context) {
17 super(context,DB_NAME,null,DB_VERSION);
18 }
19
20 21 * 创建数据库,指定数据库名称,版本号
22 * @param db
23 24 @Override
25 void onCreate(SQLiteDatabase db) {
26 String sql="create table person(_id integer primary key autoincrement not null,name char(10),nickname char(10))"27 db.execSQL(sql);
28 29
30 31 * 数据库升级
32 33 oldVersion
34 newVersion
35 36 37 void onUpgrade(SQLiteDatabase db,1)">int oldVersion,1)">int newVersion) {
38 if(newVersion>oldVersion){
39 onCreate(db);
40 }
41 42 }
1 2 * 新增
*
v
5 6 add(View v) {
7 /** //一般不使用此种方法,因为execSQL方法没有返回值
String sql="insert into person(name,nickname)values('宋江','及时雨')";
9 db.execSQL(sql);
10 11 ContentValues values = new ContentValues();
12 values.put("name","宋江");
13 values.put("nickname","及时雨"14 //返回值为插入行的行号
15 long result = db.insert("person",values);
16 if (result > 0) {
17 Toast.makeText(this,"插入成功"18 } else {
19 Toast.makeText(20 21 }
1 * 查询
query(View v) {
/*
String sql="select * from person where name=?";
Cursor cursor = db.rawQuery(sql,new String[]{"宋江"});
10 11 columns 如果为空,则表示所有列
12 Cursor cursor = db.query("person",1)">null,"name=?",1)">new String[]{"宋江"},1)">13 while (cursor.moveToNext()) {
14 int nameIndex = cursor.getColumnIndex("name"15 int nickIndex = cursor.getColumnIndex("nickname"16 String nameValue = cursor.getString(nameIndex);
17 String nickValue = cursor.getString(nickIndex);
18 String s = "name=" + nameValue + ",nickname=" + nickValue;
this adaper.swapCursor(cursor);
adaper.notifyDataSetChanged();
23 }
1 * 更新
update(View v) {
String sql="update person set nickname=? where name=?";
8
9 ContentValues values = 10 values.put("nickname","及时雨2"更新语句受影响的行数
12 int result = db.update("person",values,1)">new String[]{"宋江"});
14 Toast.makeText(15 } 16 Toast.makeText(17 18 }
* 删除
delete(View v) {
String sql="delete person where name=?";
9 受删除语句影响的行数
int result = db.delete("person",1)">12 Toast.makeText(13 } 15 16 }