sqlite增删改查

<?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:id="@+id/activity_main"
    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.example.cunli.sqlite002.MainActivity">

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="姓名" />

    <EditText
        android:id="@+id/age"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/name"
        android:hint="年龄" />

    <RadioGroup
        android:id="@+id/radioGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/age">

        <RadioButton
            android:id="@+id/male"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="男" />

        <RadioButton
            android:id="@+id/female"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="女" />
    </RadioGroup>

    <Button
        android:id="@+id/saveButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/radioGroup"
        android:onClick="saveStudent"
        android:text="插入数据" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/deleteData"
        android:onClick="deleteData"
        android:layout_marginLeft="20dp"
        android:text="删除全部数据"
        android:layout_toRightOf="@id/saveButton"
        android:layout_below="@id/radioGroup"/>
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/saveButton"
    android:hint="更新"
    android:id="@+id/updateData"/>
    <Button
        android:id="@+id/updateButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/updateData"
        android:onClick="updateStudent"
        android:text="更新"
        android:layout_marginLeft="20dp"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_toRightOf="@id/updateButton"
        android:layout_below="@id/updateData"
        android:text="取出数据"
        android:id="@+id/getData"
        android:onClick="getData"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="clearData"
        android:id="@+id/clearData"
        android:layout_below="@id/updateData"
        android:layout_toRightOf="@id/getData"
        android:text="清空表中所有数据"
        android:layout_marginLeft="10dp"/>
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/getData">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:id="@+id/linerLayout"/>

    </ScrollView>
</RelativeLayout>
package com.example.cunli.sqlite002;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
EditText nameEt,ageEt;
    RadioGroup radioGroup;
    SQLiteDatabase db;
    boolean gender = true;
    ContentValues contentValues;
    private List<Long> ids = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        contentValues = new ContentValues();
        nameEt = (EditText)findViewById(R.id.name);
        ageEt = (EditText)findViewById(R.id.age);
        radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.male){
                    gender = true;
                }else {
                    gender = false;
                }
            }
        });
        //以刻都写的方式打开或创建一个数据
        db = openOrCreateDatabase("school",SQLiteDatabase.OPEN_READWRITE,null);
        //建表的语句
        String createSQL = "CREATE TABLE IF NOT EXISTS Students (_id INTEGER NOT NULL,student_name CHAR(20) NOT NULL,age INTEGER,gender BOOLEAN,PRIMARY KEY(_id))";
        //执行建表SQL语句
        db.execSQL(createSQL);
    }
    //点击按钮事件处理
    public void saveStudent(View view){
        //创建ContentValues

        contentValues.put("student_name",nameEt.getText().toString());
        contentValues.put("age",Integer.parseInt(ageEt.getText().toString()));
        contentValues.put("gender",gender);
        //执行插入语句
        long id = db.insert("Students",null,contentValues);
        ids.add(id);
        //如果返回值为-1,则说明那个插入失败
        if (id != -1){
            Toast.makeText(this,"插入数据成功",Toast.LENGTH_SHORT).show();
        }else {
            Toast.makeText(this,"插入数据 失败",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (db!=null){
            db.close();//关闭数据库
        }
    }
//    更新数据库
    public void updateStudent(View view){
        String updateData = ((EditText)findViewById(R.id.updateData)).getText().toString();
        contentValues.put("student_name",updateData);
        //更新数据
        int num = db.update("Students",contentValues,"_id=?",new String[]{""+1});
        Toast.makeText(MainActivity.this,"更新了"+num+"条数据。",Toast.LENGTH_SHORT).show();
    }
//    查询数据
    public void getData(View view){
        LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linerLayout);
        linearLayout.removeAllViews();//显示当前数据前,清除之前的数据
        Cursor cursor = db.query("Students",new String[]{"student_name","age","gender"},null,null,null,null,"age");
        if (cursor.getCount() > 0){
            //循环获取数据
            while (!cursor.isLast()){//退出循环的条件:是否到cursor的末尾
                cursor.moveToNext();//向前移动,注意刚开始的时候,指针是在第一行数据之前的
                String name = cursor.getString(0);
                int age = cursor.getInt(1);
                int gender = cursor.getInt(2);
                TextView textView = new TextView(MainActivity.this);
                textView.setText(name+":"+age+":"+(gender==1?"男":"女"));

                linearLayout.addView(textView);

            }
        }else {
            Toast.makeText(MainActivity.this,"表中没有数据",Toast.LENGTH_SHORT).show();
        }

    }

    //    删除全部数据
    public void deleteData(View view){
        String[] arr = new String[ids.size()];
        for (int i = 0; i < ids.size(); i++) {
            int delId = db.delete("Students","_id = ? ",new String[]{ids.get(i).toString()});
            Log.e("log","----------------"+delId);
        }
        Toast.makeText(MainActivity.this,"全部数据已经删除",Toast.LENGTH_SHORT).show();
    }
//    清空表中所有数据
    public void clearData(View view){
        int delId = db.delete("Students",null,null);
        Log.e("log","----------------"+delId);

        Toast.makeText(MainActivity.this,"表中全部数据已清空",Toast.LENGTH_SHORT).show();
    }
}

 

posted @ 2017-01-16 14:49  次序  阅读(278)  评论(0编辑  收藏  举报