增删改查

package com.example.myapplication;

import android.os.Bundle;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void add(View v) {
        StuOpenHelper helper = new StuOpenHelper(this);
        SQLiteDatabase db = helper.getWritableDatabase();
        String name = ((EditText) findViewById(R.id.et_name)).getText()
                .toString();
        int age = Integer.parseInt(((EditText) findViewById(R.id.et_age))
                .getText().toString());

        // 原生sql操作,
        // db.execSQL("insert into stuinfo (name,age) values('lisi',22)");
        // db.execSQL("insert into stuinfo (name,age) values(?,?)",new
        // Object[]{"kitty",30});
        db.execSQL("insert into stuinfo (name,age) values(?,?)", new Object[] {
                name, age });
        Toast.makeText(this, "ok", 0).show();

    }

    public void delete(View view) {
        StuOpenHelper helper = new StuOpenHelper(this);
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL("delete from stuinfo where _id=?", new Object[] { 2 });
        Toast.makeText(this, "删除成功", 0).show();

    }

    public void update(View view) {
        StuOpenHelper helper = new StuOpenHelper(this);
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL("update stuinfo set name=? where _id=?", new Object[] {
                "micky", 3 });
        Toast.makeText(this, "修改成功", 0).show();

    }

    public void search(View view) {
        StuOpenHelper helper = new StuOpenHelper(this);
        SQLiteDatabase db = helper.getWritableDatabase();
        Str
package com.example.myapplication;

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

public class StuOpenHelper extends SQLiteOpenHelper {

    public StuOpenHelper(Context context) {
        super(context, "stu.db", null, 1);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL("create table stuinfo(_id integer primary key autoincrement,name varchar(20),age integer)");

    }

    @Override
    public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
        // TODO Auto-generated method stub

    }

}

 

posted @ 2020-12-08 15:04  计算机1802王兆明  阅读(55)  评论(0编辑  收藏  举报