android利用SQLiteOpenHelper类实现对数据库的增删查改操作

本文介绍如何在Android应用中使用SQLiteOpenHelper类创建数据库、插入数据、查询数据、更新数据和删除数据的操作方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

android内部提供了SQLiteOpenHelper工具类,封装了操作内置数据库SqLite的基本方法,完成实现对数据库的增删查改操作;


首先创建项目,实现几个操作按钮;

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.sqlitedemo.MainActivity" >

    <Button 
        android:id="@+id/createDatabase"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="创建数据库"
        />
  
        <Button 
        android:id="@+id/insert"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="插入数据库"
        />
          <Button 
        android:id="@+id/update"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="更新数据"
        />
            <Button 
        android:id="@+id/query"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="查询数据"
        />
              <Button 
        android:id="@+id/delete"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="删除数据"
        />

</LinearLayout>



创建一个SQLiteOpenHelper子类实例对象MyDBhelper,完成数据库创建等初始化工作:

package com.example.sqlitedemo;

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

public class MyDBhelper extends SQLiteOpenHelper{
    

    public static  final String ID="_id";
    public static  final String NAME="name";
    public static  final String AGE="age";
    public static  final String SEX="sex";
    public static  final String TABLE_NAME="person";
    
    public MyDBhelper(Context context) {
		super(context,"persons", null,1);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		
		db.execSQL("CREATE TABLE "+TABLE_NAME+"("+
				ID+" INTEGER PRIMARY KEY AUTOINCREMENT,"
				+NAME+" TEXT NOT NULL,"
				+AGE+" INTEGER,"
				+SEX+" TEXT"+")");
		System.out.println("database created!");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		System.out.println("database update!");
	}
}


SQLiteOpenHelper构造方法中,四个参数分别表示context 上下文对象,name 初始化数据库名称,factory CursorFactory对象,version 数据库版本,默认是1,版本变化会执行回调函数onUpgrade()方法!


MyDBhelper继承了SQLiteOpenHelper,并且重写了父类构造方法和两个回调方法;当实例化一个MyDBhelper对象,并通过该对象获取一个可写SQLiteDatabase实例的时候,会执行回调方法onCreate();当构造函数中的version改变的时候会执行onUpgrade()方法;


回到mainActivity中实现具体功能:



package com.example.sqlitedemo;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
    private Button createDatabase;
    private Button insert;
    private Button query;
    private Button update;
    private Button delete;
    private MyDBhelper dbHelper;
    SQLiteDatabase db;
    Cursor cursor;
    public static  int counter=0;
    public String name,sex;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}
	
	private void initView(){
		
		createDatabase =(Button) findViewById(R.id.createDatabase);
		insert=(Button) findViewById(R.id.insert);
		query=(Button) findViewById(R.id.query);
		update=(Button) findViewById(R.id.update);
		delete=(Button) findViewById(R.id.delete);
		
		createDatabase.setOnClickListener(this);
		insert.setOnClickListener(this);
		query.setOnClickListener(this);
		update.setOnClickListener(this);
		delete.setOnClickListener(this);
		
	}
	
	//创建数据库
	private void createDB(){
		dbHelper =new MyDBhelper(this);
		db=dbHelper.getWritableDatabase();
		Toast.makeText(this, "database created!", Toast.LENGTH_SHORT);
	}
	
	//插入数据库;
	private void insertDB(){
		counter++;
		name="用户"+counter;
		if(counter%2==0){
			sex="male";
		}else{
			sex="female";
		}
		
		dbHelper =new MyDBhelper(this);
		db=dbHelper.getWritableDatabase();
		ContentValues cv =new ContentValues();
		cv.put("name",name);
		cv.put("age",26);
		cv.put("sex",sex);
		db.insert(MyDBhelper.TABLE_NAME, null, cv);
		Toast.makeText(this, name+"添加成功", Toast.LENGTH_SHORT).show();
		db.close();
	}
	
	//查询数据库
	private void  queryDB(){
		dbHelper =new MyDBhelper(this);
		SQLiteDatabase rdb=dbHelper.getReadableDatabase();
		cursor=rdb.query(MyDBhelper.TABLE_NAME, null, null, null, null, null, null);
		StringBuffer sb=new StringBuffer();
		
		while(cursor.moveToNext()){
			String rs=cursor.getInt(cursor.getColumnIndex(MyDBhelper.ID))+","+cursor.getString(cursor.getColumnIndex(MyDBhelper.NAME))+","+cursor.getInt(cursor.getColumnIndex(MyDBhelper.AGE))+","+cursor.getString(cursor.getColumnIndex(MyDBhelper.SEX))+"\n";
		    sb.append(rs);
		}
		
		Toast.makeText(this, sb.toString(), Toast.LENGTH_LONG).show();
		db.close();
	}
	
	//删除数据
	private void deleteDB(){
		dbHelper =new MyDBhelper(this);
		db=dbHelper.getWritableDatabase();
		String whereClause="_id>?";
		String[] whereArgs={String.valueOf(1)};
		db.delete(MyDBhelper.TABLE_NAME, whereClause, whereArgs);
		db.close();
		Toast.makeText(this, "删除成功!", Toast.LENGTH_SHORT).show();
	}
	
	//更新数据
	private void updateDB(){
		dbHelper =new MyDBhelper(this);
		db=dbHelper.getWritableDatabase();
		ContentValues values =new ContentValues();
		values.put("age", 21);
		String whereClause="name=?";
		String[] whereArgs={String.valueOf("小强")};
		db.update(MyDBhelper.TABLE_NAME, values, whereClause, whereArgs);
		db.close();
		Toast.makeText(this, "数据更新成功!", Toast.LENGTH_SHORT).show();
	}

	public void onClick(View v) {
		
		switch (v.getId()) {
		case R.id.createDatabase:
			createDB();
			break;
       case R.id.insert:
    	   insertDB();
			break;
       case R.id.query:
			queryDB();
			break;
       case R.id.update:
    	   updateDB();
			break;
       case R.id.delete:
    	   deleteDB();
			break;
		}
	}
	
	
}


效果:





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值