package com.moliying.a46_sqlite;
import android.app.FragmentManager;
import android.provider.BaseColumns;
public interface PersonEntry extends BaseColumns{
//把表结构的字段名,表名定义为常量,表person 的元数据
public static final String TABLE_PERSON = "person";
public static final String NAME = "name";
public static final String AGE = "age";
public static final String SEX = "sex";
public static final String MONEY = "money";
}
package com.moliying.a46_sqlite;
public class Person {
private int id;
private String name;
private int age;
private String sex;
private double money;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
public Person() {
}
public Person(String name, int age, String sex, double money) {
this.name = name;
this.age = age;
this.sex = sex;
this.money = money;
}
public Person(int id, String name, int age, String sex, double money) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
this.money = money;
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
", money=" + money +
'}';
}
}
package com.moliying.a46_sqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* company moliying.com
* author vince
* 2016/7/20
*/
public class DatabaseAdapter {
private DbSQLiteOpenHelper dbHelper;
public DatabaseAdapter(Context context){
dbHelper = new DbSQLiteOpenHelper(context);
}
/**
* 如果程序中有两条以上的SQL操作,那么必须使用事务处理,来保正所有的操作要么一起失败,
* 要么一起成功
*/
public void transaction(Person pNew,Person pUpdate){
String sql1 = "insert into person(name,age,sex,money)values(?,?,?,?)";
String sql2 = "update person set name=?,age=?,sex=?,money=? where _id=?";
SQLiteDatabase db = dbHelper.getWritableDatabase();
db.beginTransaction();//开始一个事务
try{
db.execSQL(sql1);
db.execSQL(sql2);
db.setTransactionSuccessful();//设置事务成功的标记
}finally {
db.endTransaction();//判断事务标记是否为true,如果为true则提交事务,如果为false则回滚事务
}
db.close();
}
public void add(Person p){
SQLiteDatabase db = dbHelper.getWritableDatabase();
// String sql = "insert into person(name,age,sex,money)values(?,?,?,?)";
// db.execSQL(sql,new Object[]{p.getName(),p.getAge(),p.getSex(),p.getMoney()});
// db.close();
ContentValues values = new ContentValues();
values.put(PersonEntry.NAME,p.getName());
values.put(PersonEntry.AGE,p.getAge());
values.put(PersonEntry.SEX,p.getSex());
values.put(PersonEntry.MONEY,p.getMoney());
//拼SQL语句,insert into person(name) values(null)
db.insertOrThrow(PersonEntry.TABLE_PERSON,PersonEntry.NAME,values);
db.close();
}
public void update(Person p){
SQLiteDatabase db = dbHelper.getWritableDatabase();
// String sql = "update person set name=?,age=?,sex=?,money=? where _id=?";
// db.execSQL(sql,new Object[]{p.getName(),p.getAge(),p.getSex(),p.getMoney(),p.getId()});
// db.close();
ContentValues values = new ContentValues();
values.put(PersonEntry.NAME,p.getName());
values.put(PersonEntry.AGE,p.getAge());
values.put(PersonEntry.SEX,p.getSex());
values.put(PersonEntry.MONEY,p.getMoney());
String whereClause = PersonEntry._ID+"=?";
String[] whereArgs = {String.valueOf(p.getId())};
//更新,参数(表名,更新的值集合(ContentValues),条件,条件的值)
db.update(PersonEntry.TABLE_PERSON,values,whereClause,whereArgs);
db.close();
}
public void delete(int id){
SQLiteDatabase db = dbHelper.getWritableDatabase();
// String sql = "delete from person where _id=?";
// db.execSQL(sql,new Object[]{id});
// db.close();
String whereClause = PersonEntry._ID+"=?";
String[] whereArgs = {String.valueOf(id)};
db.delete(PersonEntry.TABLE_PERSON,whereClause,whereArgs);
db.close();
}
public Person findById(int id){
SQLiteDatabase db = dbHelper.getReadableDatabase();
// String sql = "select _id,name,age,sex,money from person where _id=?";
//查询后返回Cursor游标
// Cursor c = db.rawQuery(sql,new String[]{String.valueOf(id)});
String selection = PersonEntry._ID+"=?";
String[] selectArgs = {String.valueOf(id)};
//参数:表名,字符串数组(查询的列名null表示所有列),查询条件,查询条件的值,分组,分组条件,排序,分页
Cursor c = db.query(PersonEntry.TABLE_PERSON,null,selection,selectArgs,null,null,null,null);
Person p = null;
if(c!=null){
if(c.moveToFirst()){
p = new Person();
p.setId(c.getInt(0));
p.setName(c.getString(1));
p.setAge(c.getInt(2));
p.setSex(c.getString(3));
p.setMoney(c.getDouble(4));
}
}
c.close();
db.close();
return p;
}
public ArrayList<Person> findAll(){
SQLiteDatabase db = dbHelper.getReadableDatabase();
String sql = "select _id,name,age,sex,money from person";
// 查询后返回Cursor游标
Cursor c = db.rawQuery(sql,null);
// Cursor c = db.query(PersonEntry.TABLE_PERSON,null,null,null,null,null,null,null);
ArrayList<Person> list = new ArrayList<>();
Person p = null;
if(c!=null){
while(c.moveToNext()){
p = new Person();
p.setId(c.getInt(0));
p.setName(c.getString(1));
p.setAge(c.getInt(2));
p.setSex(c.getString(3));
p.setMoney(c.getDouble(4));
list.add(p);
}
}
c.close();
db.close();
return list;
}
/**
* 数据库助手类
*/
private static class DbSQLiteOpenHelper extends SQLiteOpenHelper{
private static final String TAG = "DBSQLiteOpenHelper";
private static final String CREATE_TABLE = "create table person(_id integer primary key autoincrement," +
"name text,age int,sex text,money real)";
private static final String DB_NAME = "mly.db";
private static final int VERSION = 1;
public DbSQLiteOpenHelper(Context context) {
//上下文,数据库名,创建游标的工厂(null表示使用默认游标工厂),版本号
super(context, DB_NAME, null, VERSION);
Log.i(TAG,"DbSQLiteOpenHelper");
}
//用于创建数据库时调用
//SQLiteDatabase 操作数据库表的工具类
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
Log.i(TAG,"onCreate");
}
//更新数据库时调用的方法
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i(TAG,"onUpgrade:oldVersion="+oldVersion+",newVersion:"+newVersion);
}
}
}
package com.moliying.a46_sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* 数据库助手类
*/
public class DBSQLiteOpenHelper extends SQLiteOpenHelper{
private static final String TAG = "DBSQLiteOpenHelper";
private static final String CREATE_TABLE = "create table person(_id integer primary key autoincrement," +
"name text,age int,sex text,money real)";
private static final String DB_NAME = "mly.db";
private static final int VERSION = 2;
public DBSQLiteOpenHelper(Context context) {
//上下文,数据库名,创建游标的工厂(null表示使用默认游标工厂),版本号
super(context, DB_NAME, null, VERSION);
}
//用于创建数据库时调用
//SQLiteDatabase 操作数据库表的工具类
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
Log.i(TAG,"onCreate");
}
//更新数据库时调用的方法
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i(TAG,"onUpgrade:oldVersion="+oldVersion+",newVersion:"+newVersion);
}
}
package com.moliying.a46_sqlite;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private DatabaseAdapter dbAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbAdapter = new DatabaseAdapter(this);
}
/**
* 事务操作
* @param view
*/
public void transactionClick(View view){
dbAdapter.transaction(new Person("yp",20,"男",100d),new Person(1,"hcc",23,"男",20));
Toast.makeText(MainActivity.this, "事务操作成功", Toast.LENGTH_SHORT).show();
}
public void addClick(View view){
Person p = new Person("hc",18,"男",50.5d);
dbAdapter.add(p);
Toast.makeText(MainActivity.this, "add success", Toast.LENGTH_SHORT).show();
}
public void updateClick(View view){
Person p = new Person(1,"hc",18,"男",55.5d);
dbAdapter.update(p);
Toast.makeText(MainActivity.this, "update success", Toast.LENGTH_SHORT).show();
}
public void deleteClick(View view){
dbAdapter.delete(1);
Toast.makeText(MainActivity.this, "delete success", Toast.LENGTH_SHORT).show();
}
public void findByIdClick(View view){
Person p = dbAdapter.findById(1);
Toast.makeText(MainActivity.this, p.toString(), Toast.LENGTH_SHORT).show();
}
public void findAllClick(View view){
ArrayList<Person> list = dbAdapter.findAll();
Toast.makeText(MainActivity.this, list.toString(), Toast.LENGTH_SHORT).show();
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.moliying.a46_sqlite.MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="add"
android:onClick="addClick"
android:id="@+id/button"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="update"
android:onClick="updateClick"
android:id="@+id/button2"
android:layout_below="@+id/button"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="delete"
android:onClick="deleteClick"
android:id="@+id/button3"
android:layout_below="@+id/button2"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="find by id"
android:onClick="findByIdClick"
android:id="@+id/button4"
android:layout_below="@+id/button3"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="find All"
android:onClick="findAllClick"
android:id="@+id/button5"
android:layout_below="@+id/button4"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="事务操作"
android:onClick="transactionClick"
android:id="@+id/button6"
android:layout_below="@+id/button5"
android:layout_alignParentStart="true" />
</RelativeLayout>