日期:2014-05-16  浏览次数:20497 次

Android SQLite数据库的添、删、查、改(简洁新手专用)

前言
         欢迎大家我分享和推荐好用的代码段~~
声明
         欢迎转载,但请保留文章原始出处:
         CSDN:
http://www.csdn.net
         雨季o莫忧离:http://blog.csdn.net/luckkof

正文

 

首先创建一个类MyOpenHelper,继承自SQLiteOpenHelper,用来打开或创建一个数据库

MyOpenHelper 

package com.SQLiteTest3;

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

publicclass MyOpenHelper extends SQLiteOpenHelper {
    String sql ="create table if not exists TestUsers"+
    "(id int primary key,name varchar,sex varchar)";

    public MyOpenHelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, factory, version);
        // TODO Auto-generated constructor stub
    }

    @Override
    publicvoid onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        db.execSQL(sql);

    }

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

    }

}

然后是实现代码:

package com.SQLiteTest3;

import android.app.Activity;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;

publicclass SQLiteTest3 extends Activity {
    Button btnInsert;
    Button btnDelete;
    Button btnUpdate;
    Button btnSelect;
    EditText etName;
    EditText etSex;
    TextView tvShowContent;
    MyOpenHelper OpenHelper;
    SQLiteDatabase db =null;
    publicstaticfinal String DB_NAME ="DBTest";

    View.OnClickListener btnInsertListener =new View.OnClickListener() {
        
        @Override
        publicvoid onClick(View v) {
            // TODO Auto-generated method stub
            InsertTb();
        }
    };
    View.OnClickListener btnDeleteListener =new View.OnClickListener() {
        
        @Override
        publicvoid onClick(View v) {
            // TODO Auto-generated method stub
            DeleteTb();
        }
    };
    View.OnClickListener btnUpdateListener =new View.OnClickListener() {
        
        @Override
        publicvoid onClick(View v) {
            // TODO Auto-generated method stub
            UpdateTb();
        }
    };
    View.OnClickListener btnSelectListener =new View.OnClickListener() {
        
        @Override
        publicvoid onClick(View v) {
            // TODO Auto-generated method stub
            Select();
        }
    };
    /** Called when the activity is first created. */
    @Override
    publicvoid onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        OpenHelper =new MyOpenHelper(this, DB_NAME, null, 1);
        btnInsert = (Button) findViewById(R.id.main_btn_inser