SQLite

来源:互联网 发布:fc2域名用不了2017 编辑:程序博客网 时间:2024/04/26 18:32
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:id="@+id/activity_main"    android:orientation="vertical"    android:background="@mipmap/zx"    android:layout_width="match_parent"    android:layout_height="match_parent">    <TextView        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:textSize="20sp"        android:textColor="#0a9f19"        android:gravity="center_horizontal"        android:text="SQLite数据库存储学生" />    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="请输入姓名"        android:id="@+id/et_name"/>    <EditText        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:hint="请输入性别"        android:id="@+id/et_sex"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="添加"        android:background="#b60712"        android:onClick="clickBtn"        android:id="@+id/btn_save"/>    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:background="#f5f503"        android:text="查询"        android:onClick="clickBtn"        android:id="@+id/btn_select"/>    <ListView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:id="@+id/tv_msg"        ></ListView>

</LinearLayout>

package com.example.mysqlite;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.Button;import android.widget.EditText;import android.widget.ListView;import java.util.ArrayList;public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {    private EditText et_name,et_sex;    private Button btn_save,btn_select;    private ListView listView;    private ArrayList<String> list;    private ArrayAdapter<String> mAdapter;    private MySQLiteUtils mMySQLiteUtils;    private ArrayList<Student> mStudents;//从表中查询到的所有的数据    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();    }    //实例化所有控件    private void initView() {        mMySQLiteUtils = MySQLiteUtils.getInstance(this);        et_name = (EditText) findViewById(R.id.et_name);        et_sex = (EditText) findViewById(R.id.et_sex);        btn_save = (Button) findViewById(R.id.btn_save);        btn_select = (Button) findViewById(R.id.btn_select);        listView = (ListView) findViewById(R.id.tv_msg);        list = new ArrayList<>();        mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);        listView.setAdapter(mAdapter);        listView.setOnItemClickListener(this);        listView.setOnItemLongClickListener(this);    }    public void clickBtn(View view) {        switch (view.getId()){            case R.id.btn_save://保存数据                saveStudent();                break;            case R.id.btn_select://查询数据                queyStudent();                break;        }    }    //查询一张表    private void queyStudent() {        mStudents = mMySQLiteUtils.queyStudent();        list.clear();        for (int i = 0; i <mStudents.size() ; i++) {            list.add(mStudents.get(i).toString());        }        mAdapter.notifyDataSetChanged();    }    private void saveStudent() {        String name =  et_name.getText().toString();        String sex = et_sex.getText().toString();        Student student = new Student(name,sex);        mMySQLiteUtils.addStudent(student);    }    //点击修改数据    @Override    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {        mMySQLiteUtils.upDateStudent(mStudents.get(i).getName(),new Student("裴浩宇",""));        queyStudent();    }    @Override    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {        mMySQLiteUtils.deletStudent(mStudents.get(i).getName());        queyStudent();        return true;    }}


package com.example.mysqlite;/** * Created by 帅比浩宇 on 2017/12/4. */public class MySQLiteConlums {    public static final String TABLE_NAME = "Student";    public static  final String NAME="name";    public static final String SEX="sex";}



package com.example.mysqlite;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;/** * Created by 帅比浩宇 on 2017/12/4. * * 上下文对象 * name   数据库的名称 * factory   工厂   null * version   版本号  数据库的版本号 */    public class MySQliteOpenHelper extends SQLiteOpenHelper {    public static final  int VEISION=1;    public  static final String SQLITE_NAME="student.db";    public MySQliteOpenHelper(Context context) {        super(context,SQLITE_NAME, null, VEISION);    }    //创建表    @Override    public void onCreate(SQLiteDatabase sqLiteDatabase) {       /**创建Student表   字段  _id自增 ,name sex*/        sqLiteDatabase.execSQL("create table if not exists Student(_id INTEGER primary key autoincrement,name varchar(20) not null,sex varchar(2))");    }    /**更新数据库*/    @Override    public void onUpgrade(SQLiteDatabase db, int i, int i1) {    }}




package com.example.mysqlite;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import java.util.ArrayList;/** * Created by 帅比浩宇 on 2017/12/4. * 自己封装的工具类  主要的任务就是用来操作表的 */public class MySQLiteUtils {    private static  MySQLiteUtils mMySQLiteUtils;    private MySQliteOpenHelper openHelper;//主要用途是获取SQLiteDatabase的对象    private MySQLiteUtils(Context mContext){        openHelper = new MySQliteOpenHelper(mContext);//    }    public static  synchronized MySQLiteUtils getInstance(Context mContext){        if(mMySQLiteUtils==null){            mMySQLiteUtils = new MySQLiteUtils(mContext);        }        return mMySQLiteUtils;    }    //自己封装一个方法   往student这个表中添加一个学生对象    public void addStudent(Student student){        SQLiteDatabase sqLiteDatabase = null;//操作表的        try {            sqLiteDatabase = openHelper.getReadableDatabase();//获取SQLiteDatabase的对象            ContentValues contentValues = new ContentValues();            contentValues.put(MySQLiteConlums.NAME,student.getName());            contentValues.put(MySQLiteConlums.SEX,student.getSex());            sqLiteDatabase.insert(MySQLiteConlums.TABLE_NAME,null,contentValues);//往表中插入一条数据        }catch (Exception t){        }finally {            sqLiteDatabase.close();        }//        sqLiteDatabase.execSQL("");    }    //封装一个查询表的方法    public ArrayList<Student> queyStudent(){        ArrayList<Student> list = new ArrayList<>();        SQLiteDatabase sqLiteDatabase = null;        Cursor cursor = null;        try{            sqLiteDatabase = openHelper.getReadableDatabase();            //查询表中的所有数据全部都存入到cursor            cursor = sqLiteDatabase.query(MySQLiteConlums.TABLE_NAME, new String[]{MySQLiteConlums.NAME, MySQLiteConlums.SEX}, null, null, null, null, null, null);//            sqLiteDatabase.execSQL("");            while (cursor.moveToNext()){                int nameIndex = cursor.getColumnIndex(MySQLiteConlums.NAME);//列号                int sexIndex = cursor.getColumnIndex(MySQLiteConlums.SEX);//                String name =  cursor.getString(nameIndex);                String sex = cursor.getString(sexIndex);                Student student = new Student(name,sex);                list.add(student);            }            return  list;        }catch (Exception t){        }finally {            cursor.close();            sqLiteDatabase.close();        }        return  null;    }    //删除一条学生信息    public  boolean deletStudent(String name){        SQLiteDatabase sqLiteDatabase = null;        sqLiteDatabase= openHelper.getReadableDatabase();        int count = sqLiteDatabase.delete(MySQLiteConlums.TABLE_NAME, MySQLiteConlums.NAME + "='" + name+"'", null);        if(count!=0){            return true;        }        return false;    }    //修改一条学生信息    public void upDateStudent(String name,Student stu){        SQLiteDatabase sqlitedatabase = null;        sqlitedatabase = openHelper.getReadableDatabase();        ContentValues cv = new ContentValues();        cv.put(MySQLiteConlums.NAME,stu.getName());        cv.put(MySQLiteConlums.SEX,stu.getSex());        int count = sqlitedatabase.update(MySQLiteConlums.TABLE_NAME, cv, MySQLiteConlums.NAME + "='" + name+"'", null);    }}




package com.example.mysqlite;/** * Created by 帅比浩宇 on 2017/12/4. */public class Student {    private String name;    private String sex;    public Student(String name, String sex) {        this.name = name;        this.sex = sex;    }    public String getName() {        return name;    }    public String getSex() {        return sex;    }    public void setName(String name) {        this.name = name;    }    public void setSex(String sex) {        this.sex = sex;    }    @Override    public String toString() {        return "Student{" + "name='" + name + '\'' + ", sex='" + sex + '\'' + '}';    }}

原创粉丝点击