android 数据库操作

直奔主题,android要想使用数据库SQLite,那就得写一个工具类来继承自SQLiteOpenhelper,并实现onCreate方法。并且编写要用的数据库操作如增删改查。

直接上代码了

package com.icedcap.dbtest;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DbHelper extends SQLiteOpenHelper {

	private static final String TAG = "DBtest";
	private static final String TABLE1 = "person";
	private SQLiteDatabase db = null;
	private Cursor cursor = null;

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

	// 建表
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		this.db = db;
		db.execSQL("CREATE TABLE " + TABLE1 + " (" + "id" + " text not null, "
				+ "name" + " text not null, " + "age" + " text" + ");");
	}

	// 增
	public void insert(ContentValues values) {
		SQLiteDatabase db = getWritableDatabase();
		System.out.println("values" + values.get("id") + values.get("name")
				+ values.get("age"));
		db.insert(TABLE1, null, values);
		Log.i(TAG, "增加一行");
		db.close();
	}

	// 删除某一行
	public void delete(int id) {
//		if (db == null) {
		SQLiteDatabase db = getWritableDatabase();
//		}
		db.delete(TABLE1, "id=?", new String[] { String.valueOf(id) });
		Log.i(TAG, "删除一行");
	}

	// 更新某一行
	public void update(ContentValues values, int id) {
		SQLiteDatabase db = getWritableDatabase();
		db.update(TABLE1, values, "id=?", new String[] { String.valueOf(id) });
		db.close();
		Log.i(TAG, "更新一行");
	}

	// 按id查询
	public Cursor query(int id) {
		SQLiteDatabase db = getWritableDatabase();
		System.out.println("id---->" + id);
		cursor = db.query(TABLE1, null, "id=?",
				new String[] { String.valueOf(id) }, null, null, null);
		Log.i(TAG, "按id查询一行");
		return cursor;
	}

	public Cursor query() {
		SQLiteDatabase db = getWritableDatabase();
		cursor = db.query(TABLE1, null, null, null, "id", null, null);
		Log.i(TAG, "查询所有");
		return cursor;
	}

	// 按sql语句操作数据库
	public void handleBySql(String sql) {
		SQLiteDatabase db = getWritableDatabase();
		db.execSQL(sql);
		Log.i(TAG, "执行sql语句");
	}

	// 关闭数据库
	public void close() {
		if (db != null) {
			db.close();
			db = null;
		}
		if (cursor != null) {
			cursor.close();
			cursor = null;
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

}

在主activity中调用工具类

package com.icedcap.dbtest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

@SuppressLint("NewApi")
public class MainActivity extends Activity implements OnClickListener {

	private Button add, delete, update, query, exec, display;
	private EditText edittext;
	private TextView textview;
	private static final String DB = "ddd";
	private DbHelper dbHelper = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		dbHelper = new DbHelper(this, DB, null, 1);
		initView();
	}

	private void initView() {
		add = (Button) findViewById(R.id.add);
		add.setOnClickListener(this);
		delete = (Button) findViewById(R.id.delete);
		delete.setOnClickListener(this);
		update = (Button) findViewById(R.id.update);
		update.setOnClickListener(this);
		query = (Button) findViewById(R.id.query);
		query.setOnClickListener(this);
		exec = (Button) findViewById(R.id.exec);
		exec.setOnClickListener(this);
		display = (Button) findViewById(R.id.display);
		display.setOnClickListener(this);
		edittext = (EditText) findViewById(R.id.edittext);
		textview = (TextView) findViewById(R.id.textview);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.add:
			insert();
			break;
		case R.id.delete:
			delete();
			break;
		case R.id.update:
			update();
			break;
		case R.id.query:
			query();
			break;
		case R.id.exec:
			exec();
			break;
		case R.id.display:
			display();
			break;
		default:
			break;
		}
	}

	// 插入操作需要按顺序填写各个字段的内容并用,隔开
	@SuppressLint("NewApi")
	private void insert() {
		// dbHelper.getWritableDatabase();
		ContentValues values = new ContentValues();
		String[] text = edittext.getText().toString().split(",");
		String id = text[0];
		System.out.println("id+++>" + id);
		if (id != null && !id.isEmpty()) {
			String name = text[1];
			String age = text[2];
			values.put("id", id);
			values.put("name", name);
			values.put("age", age);
			dbHelper.insert(values);
		} else {
			textview.setText("请输入正确的执行条件!。。。");
			textview.setTextColor(Color.RED);
		}

	}

	// 删除某一行需要填写id
	private void delete() {
		String id = edittext.getText().toString();
		if (id != null && !id.isEmpty()) {
			dbHelper.delete(Integer.parseInt(id));
		} else {
			textview.setText("请输入正确的执行条件!。。。");
			textview.setTextColor(Color.RED);
		}

	}

	// 执行具体的sql语句
	private void exec() {
		String sql = edittext.getText().toString();
		if (sql != null && !sql.isEmpty()) {
			dbHelper.handleBySql(sql);
		} else {
			textview.setText("请输入正确的执行条件!。。。");
			textview.setTextColor(Color.RED);
		}

	}

	// 修改操作需要按顺序填写各个字段的内容并用,隔开并且最后要填写修改某一行的id
	private void update() {
		ContentValues values = new ContentValues();
		String[] text = edittext.getText().toString().split(",");
		String id = text[0];

		if (id != null && !id.isEmpty()) {
			String name = text[1];
			String age = text[2];
			int moId = Integer.parseInt(text[3]);
			values.put("id", id);
			values.put("name", name);
			values.put("age", age);
			dbHelper.update(values, moId);
		} else {
			textview.setText("请输入正确的执行条件!。。。");
			textview.setTextColor(Color.RED);
		}

	}

	// 按id查询某一行
	private void query() {
		String selectid = edittext.getText().toString();
		if (selectid != null && !selectid.isEmpty()) {
			Cursor cursor = dbHelper.query(Integer.parseInt(selectid));
			StringBuffer text = new StringBuffer();
			if (cursor.moveToFirst()) {
				while (!cursor.isAfterLast()) {
					// cursor.move(i);
					String id = cursor.getString(cursor.getColumnIndex("id"));
					String name = cursor.getString(cursor
							.getColumnIndex("name"));
					String age = cursor.getString(cursor.getColumnIndex("age"));
					String message = "id: " + id + " name: " + name + " age: "
							+ age;
					text.append(message + "\n");
					cursor.moveToNext();
				}
				// for (int i = 0; i < cursor.getCount(); i++) {}
			}
			textview.setText(text);
			textview.setTextColor(Color.BLACK);
		} else {
			textview.setText("请输入正确的执行条件!。。。");
			textview.setTextColor(Color.RED);
		}

	}

	// 显示所有数据
	private void display() {
		// 解析游标
		Cursor cursor = dbHelper.query();
		StringBuffer text = new StringBuffer();
		if (cursor.moveToFirst()) {
			while (!cursor.isAfterLast()) {
				// cursor.move(i);
				String id = cursor.getString(cursor.getColumnIndex("id"));
				String name = cursor.getString(cursor.getColumnIndex("name"));
				String age = cursor.getString(cursor.getColumnIndex("age"));
				String message = "id: " + id + " name: " + name + " age: "
						+ age;
				text.append(message + "\n");
				cursor.moveToNext();
			}
			// for (int i = 0; i < cursor.getCount(); i++) {}
		}
		textview.setText(text);
		textview.setTextColor(Color.BLACK);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (dbHelper != null) {
			dbHelper.close();
			dbHelper = null;
		}
	}

}

最后效果图:


总结:

数据库操作有两种方法一是直接通过sql语句调用execSQL(sql)来操作。第二种就是直接调用API给出的具体操作方法。

数据库的通信是要有开关的本操作是具体情况而定的。

游标的解析要通过while (!cursor.isAfterLast())来遍历,否则会出现越界异常。


点击下载demo


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android中进行数据库操作的步骤如下: 1. 创建一个自定义的类,继承SQLiteOpenHelper类,并实现onCreate()和onUpgrade()方法。在onCreate()方法中,通过执行SQL语句创建表格。例如,可以使用execSQL()方法执行CREATE TABLE语句来创建表格。\[3\] 2. 在自定义的SQLiteOpenHelper类中,重写onOpen()方法,可以在该方法中进行一些数据库打开时的操作。\[3\] 3. 在需要进行数据库操作的地方,创建一个SQLiteOpenHelper的实例,并调用getWritableDatabase()或getReadableDatabase()方法获取一个可写或可读的数据库对象。\[3\] 4. 使用获取到的数据库对象,可以进行插入、查询、更新和删除等数据库操作。例如,可以使用execSQL()方法执行SQL语句来插入、更新或删除数据。\[1\] 5. 在使用完数据库后,记得调用close()方法关闭数据库连接,释放资源。\[3\] 综上所述,Android数据库操作的步骤包括创建自定义的SQLiteOpenHelper类、实现数据库的创建和升级方法、获取数据库对象、执行数据库操作、关闭数据库连接。 #### 引用[.reference_title] - *1* *3* [Android数据库操作](https://blog.csdn.net/weixin_43244265/article/details/107871897)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [Android 连接MySql数据库步骤](https://blog.csdn.net/m0_62321937/article/details/129905218)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值