关于安卓SQLlite的使用

主Activity

package com.example.administrator.fifthproject;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;
//主类
public class MainActivity extends AppCompatActivity {

    private MyDbOpenHelper myDbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //创建一个MyDbOpenHelper
        myDbHelper = new MyDbOpenHelper(this);
        //从MyDbOpenHelper中获取数据库
        SQLiteDatabase db = myDbHelper.getReadableDatabase();
        myDbHelper.changeData(db);
        //使用Cursor对象获取数据库内容
        Cursor cursor = db.query(PersonContract.PersonEntry.TABLE_NAME, null, null, null, null, null, null);
        //将Cursor内容转化并存入到List中
        List items = new ArrayList<Person>();
        while (cursor.moveToNext()) {
            long _id = cursor.getLong(cursor.getColumnIndex(PersonContract.PersonEntry._ID));
            String name = cursor.getString(cursor.getColumnIndex(PersonContract.PersonEntry.COLUMN_NAME_NAME));
            String tel = cursor.getString(cursor.getColumnIndex(PersonContract.PersonEntry.COLUMN_NAME_TEL));
            long age = cursor.getLong(cursor.getColumnIndex(PersonContract.PersonEntry.COLUMN_NAME_AGE));

            items.add(new Person(_id, name, tel, age));
        }

        cursor.close();

        ListView lvContacts = (ListView) findViewById(R.id.lv_contacts);
        //适配器
        ArrayAdapter<Person> adapter = new ArrayAdapter<Person>(this, R.layout.list_item, items) {
            @NonNull
            @Override
            public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                //获取当前位置的Item赋值给布局对象
                Person person = getItem(position);
                LayoutInflater layoutInflater = getLayoutInflater();
                View view = layoutInflater.inflate(R.layout.list_item, parent, false);
                TextView tvName = (TextView) view.findViewById(R.id.tv_name);
                TextView tvTel = (TextView) view.findViewById(R.id.tv_tel);
                tvName.setText(person.getName());
                tvTel.setText(person.getTel());

                return view;
            }
        };

        lvContacts.setAdapter(adapter);
    }

    @Override
    protected void onDestroy() {

        myDbHelper.close();
        super.onDestroy();
    }
}

数据库帮助类

package com.example.administrator.fifthproject;

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

/**
 * Created by xgqin on 14/11/2017.
 */
//MyDbOpenHelper
public class MyDbOpenHelper extends SQLiteOpenHelper {
    //创建表的语句
    private static final String SQL_CREATE_ENTRIES =
            "CREATE TABLE " + PersonContract.PersonEntry.TABLE_NAME + " (" +
                    PersonContract.PersonEntry._ID + " INTEGER PRIMARY KEY, " +
                    PersonContract.PersonEntry.COLUMN_NAME_NAME + " VARCHAR(30), " +
                    PersonContract.PersonEntry.COLUMN_NAME_TEL + " VARCHAR(20), " +
                    PersonContract.PersonEntry.COLUMN_NAME_AGE + " INTEGER" +
                    ")";
    //删除表的语句
    private static final String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS " + PersonContract.PersonEntry.TABLE_NAME;
    //数据库版本
    public static final int DATABASE_VERSION = 4;
    public static final String DATABASE_NAME = "mydb.db";
    //实例一个数据库
    public MyDbOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    public  void initDataBase(SQLiteDatabase sqLiteDatabase)
    {
    //    sqLiteDatabase.execSQL(SQL_DELETE_ENTRIES);
        initDb(sqLiteDatabase);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        // 创建表
        sqLiteDatabase.execSQL(SQL_CREATE_ENTRIES);
        //初始化表
        initDb(sqLiteDatabase);
    }
    //更新数据库
    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        sqLiteDatabase.execSQL(SQL_DELETE_ENTRIES);
        onCreate(sqLiteDatabase);
    }

    private void initDb(SQLiteDatabase db) {
        //插入方法一
        ContentValues values = new ContentValues();

        values.put(PersonContract.PersonEntry.COLUMN_NAME_NAME, "xgqin");
        values.put(PersonContract.PersonEntry.COLUMN_NAME_TEL, "13939932210");
        values.put(PersonContract.PersonEntry.COLUMN_NAME_AGE, 18);

        db.insert(PersonContract.PersonEntry.TABLE_NAME, null, values);

        values.clear();

        values.put(PersonContract.PersonEntry.COLUMN_NAME_NAME, "Eric");
        values.put(PersonContract.PersonEntry.COLUMN_NAME_TEL, "13939932211");
        values.put(PersonContract.PersonEntry.COLUMN_NAME_AGE, 19);

        db.insert(PersonContract.PersonEntry.TABLE_NAME, null, values);

        values.clear();

        values.put(PersonContract.PersonEntry.COLUMN_NAME_NAME, "Jimmy");
        values.put(PersonContract.PersonEntry.COLUMN_NAME_TEL, "13939932212");
        values.put(PersonContract.PersonEntry.COLUMN_NAME_AGE, 20);

        db.insert(PersonContract.PersonEntry.TABLE_NAME, null, values);

        values.clear();

        values.put(PersonContract.PersonEntry.COLUMN_NAME_NAME, "Johnny");
        values.put(PersonContract.PersonEntry.COLUMN_NAME_TEL, "13939932213");
        values.put(PersonContract.PersonEntry.COLUMN_NAME_AGE, 21);

        db.insert(PersonContract.PersonEntry.TABLE_NAME, null, values);

//        //插入方法一
//        ContentValues values = new ContentValues();
//
//        values.put(PersonContract.PersonEntry.COLUMN_NAME_NAME, "xgqin");
//        values.put(PersonContract.PersonEntry.COLUMN_NAME_TEL, "13939932210");
//        values.put(PersonContract.PersonEntry.COLUMN_NAME_AGE, 18);
//
//        db.insert(PersonContract.PersonEntry.TABLE_NAME, null, values);

//        values.clear();

        //插入方法二
        db.execSQL("INSERT INTO person VALUES(NULL, ?,?,?)", new Object[] {"Fancy", "13322143325", 22});


        //删除方法
        db.execSQL("delete from person where "+PersonContract.PersonEntry.COLUMN_NAME_NAME+" = ?",new String[]{"Johnny"});


        //修改方法一
        db.execSQL("update person set "+PersonContract.PersonEntry.COLUMN_NAME_TEL+" = ? where name =?",new String[]{"11111","Fancy"});

        //修改方法二
        ContentValues values1 = new ContentValues();
        values1.put(PersonContract.PersonEntry.COLUMN_NAME_TEL,11122);
        db.update("person",values1,"name=?",new String[]{"xgqin"});

    }
    //修改数据   在主类中调用即可实现修改数据
    public void changeData(SQLiteDatabase db)
    {
        ContentValues values1 = new ContentValues();
        values1.put(PersonContract.PersonEntry.COLUMN_NAME_TEL,11122);
        db.update("person",values1,"name=?",new String[]{"xgqin"});
    }
}

person实体类


package com.example.administrator.fifthproject;

/**
 * Created by xgqin on 14/11/2017.
 */
//实体类
public class Person {
    private long _id;
    private String name;
    private String tel;
    private long age;

    public long getAge() {
        return age;
    }

    public void setAge(long age) {
        this.age = age;
    }

    public Person(long id, String name, String tel, long age) {
        this._id = id;
        this.name = name;
        this.tel = tel;
        this.age = age;
    }

    public long getId() {
        return _id;
    }

    public void setId(long id) {
        this._id = id;
    }

    public String getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

实体类相关的宏


package com.example.administrator.fifthproject;

import android.provider.BaseColumns;

/**
 * Created by xgqin on 14/11/2017.
 */
//实体类的宏定义
public final class PersonContract {
    private PersonContract() {}

    public static class PersonEntry implements BaseColumns {
        public static final String TABLE_NAME = "person";
        public static final String COLUMN_NAME_NAME = "name";
        public static final String COLUMN_NAME_TEL = "tel";
        public static final String COLUMN_NAME_AGE = "age";
    }
}

主Activity布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.administrator.fifthproject.MainActivity">

    <ListView
        android:id="@+id/lv_contacts"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="2dp"
        >

    </ListView>
</LinearLayout>

List Item布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:textSize="22sp"
        />

    <TextView
        android:id="@+id/tv_tel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:textSize="16sp"
        />

</LinearLayout>


展开阅读全文

没有更多推荐了,返回首页