安卓中数据库增删改查的方法

2024-01-12 15:18

本文主要是介绍安卓中数据库增删改查的方法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!


第一步:在xml布局中编辑

<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=".MainActivity" >

   <EditText 

       android:id="@+id/et_name"

       android:layout_width="match_parent"

       android:layout_height="wrap_content"

       android:hint="请输入联系人的姓名"/>

   <EditText 

       android:layout_height="wrap_content"

       android:layout_width="match_parent"

       android:id="@+id/et_phone"

       android:hint="请输入联系人的电话"

       android:inputType="phone"/>

   <Button 

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       android:text="添加"

      android:onClick="add"/>

   <Button 

       android:layout_width="match_parent"

       android:layout_height="wrap_content"

       android:text="删除"

       android:onClick="delete"/>

   <Button 

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       android:text="修改"

       android:onClick="update"/>

   <Button 

       android:layout_width="fill_parent"

       android:layout_height="wrap_content"

       android:text="查询"

       android:onClick="query"/>

</LinearLayout>

第二步:建立一个数据库的帮助类

/**

 * 数据库创建的帮助类 类似File

 * @author Administrator

 *

 */

public class MyDBOpenHelper extends SQLiteOpenHelper {

/**

 * @param context 上下文

 * @param version

 */

public MyDBOpenHelper(Context context) {

//第二个参数数据库的名称

//第三个参数null代表的是默认的游标工厂

//第四个参数 是数据库的版本号  数据库只能升级,不能降级,版本号只能变大不能变小

super(context, "saiermeng.db", null, 2);

}

//Called when the database is created for the first time.

//当数据库第一次被创建的时候调用的方法,适合在这个方法里面把数据库的表结构定义出来.

@Override

public void onCreate(SQLiteDatabase db) {

System.out.println("oncreate 数据库被创建了. 哈哈哈哈,嘎嘎嘎------------");

//执行sql语句

db.execSQL("create table contactinfo (id integer primary key autoincrement, name varchar(20), phone varchar(20))");

}

//Called when the database needs to be upgraded.

//当数据库更新的时候调用的方法

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

System.out.println("onUpgrade 数据库被更新了. oldVersion:"+oldVersion+"--------newVersion:"+newVersion+"----");

db.execSQL("alter table contactinfo add account varchar(20)");

}

}

第三步:另建一个包,创建一个联系人信息的类

/**

 * 联系人数据库表的访问类

 */

public class ContactInfoDao {

/**

 * 数据库打开的帮助类

 */

private MyDBOpenHelper helper;

/**

 * 在构造方法里面完成 必须要用的类的初始化

 * @param context

 */

public ContactInfoDao(Context context) {

helper = new MyDBOpenHelper(context);

}

 

/**

 * 添加一条记录

 * @param name 联系人姓名

 * @param phone 联系人电话

 * @return 返回的是添加后在数据库的行号  -1代表添加失败

 */

public long add(String name, String phone){

SQLiteDatabase db = helper.getWritableDatabase();

//db.execSQL("insert into contactinfo (name,phone) values (?,?)", new Object[]{name,phone});

ContentValues values = new ContentValues();

values.put("name", name);

values.put("phone", phone);

//内部是组拼sql语句实现的.

long rowid = db.insert("contactinfo", null, values);

//记得释放数据库资源

db.close();

return rowid;

}

/**

 * 根据姓名删除一条记录

 * @param name 要删除的联系人的姓名

 * @return 返回0代表的是没有删除任何的记录 返回整数int值代表删除了几条数据

 */

public int delete(String name){

//判断这个数据是否存在.

SQLiteDatabase db = helper.getWritableDatabase();

//db.execSQL("delete from contactinfo where name=?", new Object[]{name});

int rowcount = db.delete("contactinfo", "name=?", new String[]{name});

db.close();

//再从数据库里面查询一遍,name是否还在

return rowcount;

}

/**

 * 修改联系人电话号码

 * @param newphone 新的电话号码

 * @param name 要修改的联系人姓名

 * @return 0代表一行也没有更新成功, >0 整数代表的是更新了多少行记录

 */

public int update(String newphone , String name){

SQLiteDatabase db = helper.getWritableDatabase();

//db.execSQL("update contactinfo set phone =? where name=?", new Object[]{newphone,name});

ContentValues values = new ContentValues();

values.put("phone", newphone);

int rowcount =  db.update("contactinfo", values, "name=?", new String[]{name});

db.close();

return rowcount;

}

/**

 * 查询联系人的电话号码

 * @param name 要查询的联系人

 * @return 电话号码

 */

public String getPhoneNumber(String name){

String phone = null;

SQLiteDatabase db = helper.getReadableDatabase();

//Cursor  cursor = db.rawQuery("select phone from contactinfo where name=?", new String[]{name});

Cursor  cursor =  db.query("contactinfo", new String[]{"phone"}, "name=?", new String[]{name}, null, null, null);

if(cursor.moveToNext()){//如果光标可以移动到下一位,代表就是查询到了数据

phone = cursor.getString(0);

}

cursor.close();//关闭掉游标,释放资源

db.close();//关闭数据库,释放资源

return phone;

}

}

第四步:在MainActivity.java中编辑逻辑

public class MainActivity extends Activity {

private EditText et_name;

private EditText et_phone;

private ContactInfoDao dao;

 

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

et_name = (EditText) findViewById(R.id.et_name);

et_phone = (EditText) findViewById(R.id.et_phone);

dao = new ContactInfoDao(this);

}

 

/**

 * 添加一条联系人的信息

 *

 * @param view

 */

public void add(View view) {

String name = et_name.getText().toString().trim();

String phone = et_phone.getText().toString().trim();

if (TextUtils.isEmpty(name) || TextUtils.isEmpty(phone)) {

Toast.makeText(this, "不能为空", 0).show();

return;

} else {

long id = dao.add(name, phone);

if (id == -1) {

Toast.makeText(this, "添加失败", 0).show();

} else {

Toast.makeText(this, "添加成功,在数据库的第:"+id+"", 0).show();

}

}

}

 

/**

 * 删除一条记录

 *

 * @param view

 */

public void delete(View view) {

String name = et_name.getText().toString().trim();

if (TextUtils.isEmpty(name)) {

Toast.makeText(this, "姓名不能为空", 0).show();

return;

} else {

int count = dao.delete(name);

if(count==0){

Toast.makeText(this, "删除失败,没有记录", 0).show();

}else{

Toast.makeText(this, "删除成功,删除了"+count+"条记录", 0).show();

}

}

}

 

/**

 * 修改联系人的号码

 *

 * @param view

 */

public void update(View view) {

String name = et_name.getText().toString().trim();

String phone = et_phone.getText().toString().trim();

if (TextUtils.isEmpty(name) || TextUtils.isEmpty(phone)) {

Toast.makeText(this, "不能为空", 0).show();

return;

} else {

int count = dao.update(phone, name);

if(count==0){

Toast.makeText(this, "更新失败,没有记录", 0).show();

}else{

Toast.makeText(this, "更新成功,更新了"+count+"条记录", 0).show();

}

}

}

 

/**

 * 查询

 *

 * @param view

 */

public void query(View view) {

String name = et_name.getText().toString().trim();

if (TextUtils.isEmpty(name)) {

Toast.makeText(this, "姓名不能为空", 0).show();

return;

} else {

String result = dao.getPhoneNumber(name);

Toast.makeText(this, "号码:" + result, 0).show();

}

}

}

 

第一种:这四种方法都是通过SQL语句实现的

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

 

import com.saiermeng.createdb.MyDBOpenHelper;

 

/**

 * 联系人数据库表的访问类

 */

public class ContactInfoDao {

/**

 * 数据库打开的帮助类

 */

private MyDBOpenHelper helper;

/**

 * 在构造方法里面完成 必须要用的类的初始化

 * @param context

 */

public ContactInfoDao(Context context) {

helper = new MyDBOpenHelper(context);

}

 

/**

 * 添加一条记录

 * @param name 联系人姓名

 * @param phone 联系人电话

 */

public void add(String name, String phone){

SQLiteDatabase db = helper.getWritableDatabase();

db.execSQL("insert into contactinfo (name,phone) values (?,?)", new Object[]{name,phone});

//记得释放数据库资源

db.close();

}

/**

 * 根据姓名删除一条记录

 * @param name 要删除的联系人的姓名

 */

public void delete(String name){

//判断这个数据是否存在.

SQLiteDatabase db = helper.getWritableDatabase();

db.execSQL("delete from contactinfo where name=?", new Object[]{name});

db.close();

//再从数据库里面查询一遍,name是否还在

}

/**

 * 修改联系人电话号码

 * @param newphone 新的电话号码

 * @param name 要修改的联系人姓名

 */

public void update(String newphone , String name){

SQLiteDatabase db = helper.getWritableDatabase();

db.execSQL("update contactinfo set phone =? where name=?", new Object[]{newphone,name});

db.close();

}

/**

 * 查询联系人的电话号码

 * @param name 要查询的联系人

 * @return 电话号码

 */

public String getPhoneNumber(String name){

String phone = null;

SQLiteDatabase db = helper.getReadableDatabase();

Cursor  cursor = db.rawQuery("select phone from contactinfo where name=?", new String[]{name});

if(cursor.moveToNext()){//如果光标可以移动到下一位,代表就是查询到了数据

phone = cursor.getString(0);

}

cursor.close();//关闭掉游标,释放资源

db.close();//关闭数据库,释放资源

return phone;

}

}

 

第二种:通过安卓中封装好的方法

import android.content.ContentValues;

import android.content.Context;

import android.database.Cursor;

import android.database.sqlite.SQLiteDatabase;

 

import com.saiermeng.createdb.MyDBOpenHelper;

 

/**

 * 联系人数据库表的访问类

 */

public class ContactInfoDao {

/**

 * 数据库打开的帮助类

 */

private MyDBOpenHelper helper;

/**

 * 在构造方法里面完成 必须要用的类的初始化

 * @param context

 */

public ContactInfoDao(Context context) {

helper = new MyDBOpenHelper(context);

}

 

/**

 * 添加一条记录

 * @param name 联系人姓名

 * @param phone 联系人电话

 * @return 返回的是添加后在数据库的行号  -1代表添加失败

 */

public long add(String name, String phone){

SQLiteDatabase db = helper.getWritableDatabase();

//db.execSQL("insert into contactinfo (name,phone) values (?,?)", new Object[]{name,phone});

ContentValues values = new ContentValues();

values.put("name", name);

values.put("phone", phone);

//内部是组拼sql语句实现的.

long rowid = db.insert("contactinfo", null, values);

//记得释放数据库资源

db.close();

return rowid;

}

/**

 * 根据姓名删除一条记录

 * @param name 要删除的联系人的姓名

 * @return 返回0代表的是没有删除任何的记录 返回整数int值代表删除了几条数据

 */

public int delete(String name){

//判断这个数据是否存在.

SQLiteDatabase db = helper.getWritableDatabase();

//db.execSQL("delete from contactinfo where name=?", new Object[]{name});

int rowcount = db.delete("contactinfo", "name=?", new String[]{name});

db.close();

//再从数据库里面查询一遍,name是否还在

return rowcount;

}

/**

 * 修改联系人电话号码

 * @param newphone 新的电话号码

 * @param name 要修改的联系人姓名

 * @return 0代表一行也没有更新成功, >0 整数代表的是更新了多少行记录

 */

public int update(String newphone , String name){

SQLiteDatabase db = helper.getWritableDatabase();

//db.execSQL("update contactinfo set phone =? where name=?", new Object[]{newphone,name});

ContentValues values = new ContentValues();

values.put("phone", newphone);

int rowcount =  db.update("contactinfo", values, "name=?", new String[]{name});

db.close();

return rowcount;

}

/**

 * 查询联系人的电话号码

 * @param name 要查询的联系人

 * @return 电话号码

 */

public String getPhoneNumber(String name){

String phone = null;

SQLiteDatabase db = helper.getReadableDatabase();

//Cursor  cursor = db.rawQuery("select phone from contactinfo where name=?", new String[]{name});

Cursor  cursor =  db.query("contactinfo", new String[]{"phone"}, "name=?", new String[]{name}, null, null, null);

if(cursor.moveToNext()){//如果光标可以移动到下一位,代表就是查询到了数据

phone = cursor.getString(0);

}

cursor.close();//关闭掉游标,释放资源

db.close();//关闭数据库,释放资源

return phone;

}

}

 


这篇关于安卓中数据库增删改查的方法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/598276

相关文章

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

Linux下MySQL数据库定时备份脚本与Crontab配置教学

《Linux下MySQL数据库定时备份脚本与Crontab配置教学》在生产环境中,数据库是核心资产之一,定期备份数据库可以有效防止意外数据丢失,本文将分享一份MySQL定时备份脚本,并讲解如何通过cr... 目录备份脚本详解脚本功能说明授权与可执行权限使用 Crontab 定时执行编辑 Crontab添加定

JavaScript中的高级调试方法全攻略指南

《JavaScript中的高级调试方法全攻略指南》什么是高级JavaScript调试技巧,它比console.log有何优势,如何使用断点调试定位问题,通过本文,我们将深入解答这些问题,带您从理论到实... 目录观点与案例结合观点1观点2观点3观点4观点5高级调试技巧详解实战案例断点调试:定位变量错误性能分

Python中 try / except / else / finally 异常处理方法详解

《Python中try/except/else/finally异常处理方法详解》:本文主要介绍Python中try/except/else/finally异常处理方法的相关资料,涵... 目录1. 基本结构2. 各部分的作用tryexceptelsefinally3. 执行流程总结4. 常见用法(1)多个e

JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法

《JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法》:本文主要介绍JavaScript中比较两个数组是否有相同元素(交集)的三种常用方法,每种方法结合实例代码给大家介绍的非常... 目录引言:为什么"相等"判断如此重要?方法1:使用some()+includes()(适合小数组)方法2

如何通过try-catch判断数据库唯一键字段是否重复

《如何通过try-catch判断数据库唯一键字段是否重复》在MyBatis+MySQL中,通过try-catch捕获唯一约束异常可避免重复数据查询,优点是减少数据库交互、提升并发安全,缺点是异常处理开... 目录1、原理2、怎么理解“异常走的是数据库错误路径,开销比普通逻辑分支稍高”?1. 普通逻辑分支 v

Python与MySQL实现数据库实时同步的详细步骤

《Python与MySQL实现数据库实时同步的详细步骤》在日常开发中,数据同步是一项常见的需求,本篇文章将使用Python和MySQL来实现数据库实时同步,我们将围绕数据变更捕获、数据处理和数据写入这... 目录前言摘要概述:数据同步方案1. 基本思路2. mysql Binlog 简介实现步骤与代码示例1

504 Gateway Timeout网关超时的根源及完美解决方法

《504GatewayTimeout网关超时的根源及完美解决方法》在日常开发和运维过程中,504GatewayTimeout错误是常见的网络问题之一,尤其是在使用反向代理(如Nginx)或... 目录引言为什么会出现 504 错误?1. 探索 504 Gateway Timeout 错误的根源 1.1 后端

使用shardingsphere实现mysql数据库分片方式

《使用shardingsphere实现mysql数据库分片方式》本文介绍如何使用ShardingSphere-JDBC在SpringBoot中实现MySQL水平分库,涵盖分片策略、路由算法及零侵入配置... 目录一、ShardingSphere 简介1.1 对比1.2 核心概念1.3 Sharding-Sp

MySQL 表空却 ibd 文件过大的问题及解决方法

《MySQL表空却ibd文件过大的问题及解决方法》本文给大家介绍MySQL表空却ibd文件过大的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录一、问题背景:表空却 “吃满” 磁盘的怪事二、问题复现:一步步编程还原异常场景1. 准备测试源表与数据