安卓数据库操作源码:增删改查 (安卓数据库的增删改查源码)

在Android开发中,数据库是必不可少的一部分。很多应用程序需要存储和管理数据,这就需要涉及到数据库的操作。安卓提供了SQLite数据库,是轻量级的数据库引擎,非常适合移动应用程序的嵌入式数据库。

本文将讲解安卓数据库操作的源码:增删改查。增删改查是数据库操作的基本操作,是使用SQLite数据库时必须掌握的操作。

一、创建数据库

在使用SQLite数据库前,需要创建数据库。一般情况下,创建一个新的数据库的方法是通过创建一个SQLiteOpenHelper类实例,然后调用它的getWritableDatabase()或getReadableDatabase()方法来获取SQLiteDataBase对象。

以下是一个示例代码:

“`java

public class MySQLiteOpenHelper extends SQLiteOpenHelper {

public static final String DATABASE_NAME = “test.db”; //数据库名称

public static final int DATABASE_VERSION = 1; //数据库版本

//数据库创建语句

private static final String CREATE_TABLE = “create table if not exists “

+ “person (id integer primary key autoincrement, name varchar(20), age integer)”;

public MySQLiteOpenHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

}

@Override

public void onCreate(SQLiteDatabase sqLiteDatabase) {

sqLiteDatabase.execSQL(CREATE_TABLE); //执行SQL语句,创建数据库

}

@Override

public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {

}

}

“`

在上面的代码中,MySQLiteOpenHelper类继承自SQLiteOpenHelper类。

其中,DATABASE_NAME和DATABASE_VERSION分别表示数据库的名称和版本号。在MySQLiteOpenHelper的构造函数中,调用了SQLiteOpenHelper的构造函数,并传入了数据库的名称和版本号。

CREATE_TABLE语句定义了一个person表,包括id、name和age三个字段。在onCreate()方法中,执行了这条CREATE_TABLE语句,创建了数据库。

二、插入数据

插入数据是数据库操作中最基本的操作之一。以下是一个示例代码:

“`java

public class PersonDao {

private MySQLiteOpenHelper mySQLiteOpenHelper;

public PersonDao(Context context) {

mySQLiteOpenHelper = new MySQLiteOpenHelper(context);

}

/**

* 插入一条数据

* @param person 待插入的数据

*/

public void insert(Person person) {

SQLiteDatabase db = mySQLiteOpenHelper.getWritableDatabase();

ContentValues values = new ContentValues();

values.put(“name”, person.getName());

values.put(“age”, person.getAge());

db.insert(“person”, null, values);

db.close();

}

}

“`

在上面的代码中,insert()方法是向person表中插入一条数据的方法。

通过MySQLiteOpenHelper获取SQLiteDatabase对象。

然后,使用ContentValues构建需要插入的数据。

调用db.insert()方法,将数据插入到person表中。

三、查询数据

查询数据是数据库操作中另一个基本操作。以下是一个示例代码:

“`java

public class PersonDao {

private MySQLiteOpenHelper mySQLiteOpenHelper;

public PersonDao(Context context) {

mySQLiteOpenHelper = new MySQLiteOpenHelper(context);

}

/**

* 查询所有数据

* @return 所有数据的

*/

public List queryAll() {

SQLiteDatabase db = mySQLiteOpenHelper.getReadableDatabase();

Cursor cursor = db.query(“person”, null, null, null, null, null, null);

List personList = new ArrayList();

while (cursor.moveToNext()) {

Person person = new Person();

person.setId(cursor.getInt(cursor.getColumnIndex(“id”)));

person.setName(cursor.getString(cursor.getColumnIndex(“name”)));

person.setAge(cursor.getInt(cursor.getColumnIndex(“age”)));

personList.add(person);

}

cursor.close();

db.close();

return personList;

}

}

“`

在上面的代码中,queryAll()方法是查询所有用户数据的方法。

通过MySQLiteOpenHelper获取SQLiteDatabase对象。

然后,使用db.query()方法,查询person表中的所有数据。由于想要查询所有数据,所以参数传入null。最后返回的是Cursor对象。

接着,遍历Cursor对象,通过cursor.getInt()和cursor.getString()方法获取id、name和age字段的值,并将数据封装到Person对象中。将所有Person对象添加到List中,最后返回List。

注意:使用完Cursor和SQLiteDatabase对象后,需要调用close()方法进行关闭操作。

四、修改数据

修改数据是数据库操作中很重要的一个操作。以下是一个示例代码:

“`java

public class PersonDao {

private MySQLiteOpenHelper mySQLiteOpenHelper;

public PersonDao(Context context) {

mySQLiteOpenHelper = new MySQLiteOpenHelper(context);

}

/**

* 更新数据

* @param person 待更新的数据

*/

public void update(Person person) {

SQLiteDatabase db = mySQLiteOpenHelper.getWritableDatabase();

ContentValues values = new ContentValues();

values.put(“name”, person.getName());

values.put(“age”, person.getAge());

db.update(“person”, values, “id=?”, new String[]{String.valueOf(person.getId())});

db.close();

}

}

“`

在上面的代码中,update()方法是更新person表中的数据的方法。

通过MySQLiteOpenHelper获取SQLiteDatabase对象。

然后,使用ContentValues构建需要更新的数据。

接着,使用db.update()方法,将更新的数据和需要更新的条件传入。

调用db.close()方法进行关闭操作。

五、删除数据

删除数据也是数据库操作中很重要的一个操作。以下是一个示例代码:

“`java

public class PersonDao {

private MySQLiteOpenHelper mySQLiteOpenHelper;

public PersonDao(Context context) {

mySQLiteOpenHelper = new MySQLiteOpenHelper(context);

}

/**

* 删除数据

* @param person 待删除的数据

*/

public void delete(Person person) {

SQLiteDatabase db = mySQLiteOpenHelper.getWritableDatabase();

db.delete(“person”, “id=?”, new String[]{String.valueOf(person.getId())});

db.close();

}

}

“`

在上面的代码中,delete()方法是删除person表中的数据的方法。

通过MySQLiteOpenHelper获取SQLiteDatabase对象。

然后,使用db.delete()方法,将需要删除的数据的id传入。

调用db.close()方法进行关闭操作。

六、

相关问题拓展阅读:

C# asp.net WebForm 的三层架构配合ListView实现增删改查源码

C# asp.net WebForm 的三层架构配合ListView实现增删改查源码:

1、用Access新建一个卜陆表MResume,人事管理表:

ID 姓名 性别 出生日期 工作年限 证件类型 证件号 居住地 Email 手机号码 家庭 图片 自我评价

2、控件的使用:bindingNavigator(实现分页功能), dataGridView(显示数据)

在C# WinForm 中有这一个app.config的文件,这个文件的作用可以当作web程序中的webconfig文件。

这里面可以记录数据库连接字符串

Access下数据库连接函数:

public static OleDbConnection GetConnection()

{

OleDbConnection conn = null;

string strconnectionString = “Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + AppDomain.CurrentDomain.BaseDirectory + “database\\chinabase.mdb;Persist Security Info=True”;

try

{

conn = new OleDbConnection(strconnectionString);

}

catch (Exception ex)

{

throw ex;

}

return conn;

}

3、把数据库中的数据读到dataGridView让这个控件来显示数据:

private void ResumeTest_Load(object sender, EventArgs e)

{

//手动代码把数据库中的数据显示出来

OleDbConnection conn = GetConnection();

string sqlText = “select 姓名,性别,出生日期,工作年限,证件类型,证件号,居住地,Email,手机号码,家庭,自我评价 from MResume order by id asc”;

OleDbCommand cmd = new OleDbCommand(sqlText, conn);

try

{

conn.Open();

//int i = cmd.ExecuteNonQuery();

DataTable dt = new DataTable();

OleDbDataAdapter oda = new OleDbDataAdapter(sqlText, conn);

DataSet ds = new DataSet();

// oda.Fill(dt);

// dataGridView1.DataSource = dt;

oda.Fill(ds, “ds”型袜顷);

dtInfo.Clear();

//dtInfo = null;

dtInfo = ds.Tables;

InitDataSet(dtInfo); //初始化数据

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

}

finally

{

conn.Close();

}

//设置GridView样式

// SetUpDataGridView();

dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect; //使用户能够选择行

this.dataGridView1.EditMode = DataGridViewEditMode.EditProgrammatically; //双击不能修改了,这是通过编程的方式来修改单元格内容的

this.ComboxSelect.Items.Add(“请选择类别”);

this.ComboxSelect.Items.Add(“姓名”);

this.ComboxSelect.Items.Add(“性别”);

this.ComboxSelect.SelectedText = “请选择好碧类别”;

}

更新代码如下:

private void 修改ToolStripMenuItem_Click(object sender, EventArgs e)

{

dataGridView1_DoubleClick(sender, e);

//类似于dataGridView的更新操作,也就是双击操作

}

private void dataGridView1_CellMouseDown(object

DataGridViewCellMouseEventArgs e)

{

//判断如果点击的是鼠标右键

if (e.Button == MouseButtons.Right)

{

//判断鼠标点击在数据行上

if (e.RowIndex >= 0)

{

dataGridView1.ClearSelection();

dataGridView1.Rows.Selected = true;

dataGridView1.CurrentCell

dataGridView1.Rows.Cells;

}

}

}

删除代码如下:

public bool deletDataGridViewOneLine(object sender, EventArgs e)

{

bool result = false;

Int32 selectedRowCount

dataGridView1.Rows.GetRowCount(DataGridViewElementStates.Selected);

int selectedRow = dataGridView1.SelectedRows.Index; //获得选中的某行

string MName = dataGridView1.Rows.Cells.Value.ToString().Trim();

// MessageBox.Show(MName.ToString());

DialogResult dr = MessageBox.Show(“确定要删除这条记录吗?”, “提示”, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

if (dr == DialogResult.Yes)

{

if (MName != null && MName != “”)

{

OleDbConnection conn = GetConnection();

string sqlText = “delete from MResume where 姓名=@MName”;

OleDbCommand cmd = new OleDbCommand(sqlText, conn);

cmd.Parameters.AddWithValue(“@MName”, MName);

try

{

conn.Open();

int i = cmd.ExecuteNonQuery();

result = true;

}

catch (Exception ex)

{

MessageBox.Show(“发生异常:” + ex.ToString(), “提示”);

}

查询代码如下:

private void btnSelect_Click(object sender, EventArgs e)

{

//首先进行模糊查询

string strComboxSelect = ComboxSelect.Text.Trim();

string strSearch = txtSearch.Text.Trim();

if(strComboxSelect.Equals(“请选择类别”))

{

MessageBox.Show(“请选择类别!”,”提示”);

return;

}

if (strSearch == “” || strSearch == null)

{

MessageBox.Show(“请输入查询内容!”, “提示”);

return;

}

//手动代码把数据库中的数据显示出来

OleDbConnection conn = GetConnection();

string sqlText = “select 姓名,性别,出生日期,工作年限,证件类型,证件号,居住地,Email,手机号码,家庭,自我评价 from MResume where ” + strComboxSelect + ” like ‘%”+@strSearch+”%'”;

OleDbCommand cmd = new OleDbCommand(sqlText, conn);

cmd.Parameters.AddWithValue(“@strSearch”, strSearch);

try

{

conn.Open();

//int i = cmd.ExecuteNonQuery();

DataTable dt = new DataTable();

OleDbDataAdapter oda = new OleDbDataAdapter(sqlText, conn);

oda.Fill(dt);

dataGridView1.DataSource = dt;

}

catch (Exception ex)

{

MessageBox.Show(ex.ToString());

}

安卓数据库的增删改查源码的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于安卓数据库的增删改查源码,安卓数据库操作源码:增删改查,C# asp.net WebForm 的三层架构配合ListView实现增删改查源码的信息别忘了在本站进行查找喔。


数据运维技术 » 安卓数据库操作源码:增删改查 (安卓数据库的增删改查源码)