在编程中常常会遇到数据库的操作,而Android系统内置了SQLite,它是一款轻型数据库,遵守事务ACID的关系型数据库管理系统,它占用的资源非常低,可以支持Windows/Linux/Unix等主流操作系统,同一时候可以跟非常多程序语言如C#、PHP、Java等相结合.以下先回想SQL的基本语句,再讲述Android的基本操作.

一. adb shell回想SQL语句

    首先,我感觉自己整个大学印象最深的几门课就包含《数据库》,所以想先回想SQL增删改查的基本语句.而在Android SDK中adb是自带的调试工具,它存放在sdk的platform-tools文件夹下,通过adb shell能够进入设备控制台,操作SQL语句.

G:
cd G:\software\Program software\Android\adt-bundle-windows-x86_64-20140321\sdk\platform-tools
adb shell
cd /data/data/com.example.sqliteaction/databases/
sqlite3 StuDatabase.db
.table
.schema

    例如以下所看到的我先创建了SQLiteActionproject,同一时候在project中创建了StuDatabase.db数据库.输入adb shell进入设备控制台,调用"sqlite3+数据库名"打开数据库,假设没有db文件则创建.

    然后例如以下图所看到的,能够输入SQL语句运行增删改查.注意非常easy写错SQL语句,如忘记")"或结束";"导致cmd中调用出错.

--创建Teacher表
create table Teacher (id integer primary key, name text);
--向表中插入数据
insert into Teacher (id,name) values('10001', 'Mr Wang');
insert into Teacher (id,name) values('10002', 'Mr Yang');
--查询数据
select * from Teacher;
--更新数据
update Teacher set name='Yang XZ' where id=10002;
--删除数据
delete from Teacher where id=10001;



二. SQLite数据库操作

   以下解说使用SQLite操作数据库:

    1.创建打开数据库

    使用openOrCreateDatabase函数实现,它会自己主动检測是否存在该数据库,假设存在则打开,否则创建一个数据库,并返回一个SQLiteDatabase对象.

    2.创建表

    通过定义建表的SQL语句,再调用execSQL方法运行该SQL语句实现建立表.

//创建学生表(学号,姓名,电话,身高) 主键学号
public static final String createTableStu = "create table Student (" +
"id integer primary key, " +
"name text, " +
"tel text, " +
"height real)";
//SQLiteDatabase定义db变量
db.execSQL(createTableStu);

    3.插入数据

    使用insert方法加入数据,事实上ContentValues就是一个Map,Key字段名称,Value值.

    SQLiteDatabase.insert(

        String table,         //加入数据的表名

        String nullColumnHack,//为某些空的列自己主动复制NULL

        ContentValues values  //ContentValues的put()方法加入数据

    );

//方法一
SQLiteDatabase db = sqlHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("id", "10001");
values.put("name", "Eastmount");
values.put("tel", "15201610000");
values.put("height", "172.5");
db.insert("Student", null, values);
//方法二
public static final String insertData = "insert into Student (" +
"id, name, tel, height) values('10002','XiaoMing','110','175')";
db.execSQL(insertData);

   
4.删除数据

    使用delete方法删除表中数据,当中sqlHelper是继承SQLiteDatabase自己定义类的实例.

    SQLiteDatabase.delete(

        String table,       //表名

        String whereClause, //约束删除行,不指定默认删除全部行

        String[] whereArgs  //相应数据

    );

//方法一 删除身高>175cm
SQLiteDatabase db = sqlHelper.getWritableDatabase();
db.delete("Student", "height > ?", new String[] {"175"});
//方法二
String deleteData = "DELETE FROM Student WHERE height>175";
db.execSQL(deleteData);

   
5.更新数据

    使用update方法能够改动数据,SQL+execSQL方法就不在叙述.

//小明的身高改动为180
SQLiteDatabase db = sqlHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("height", "180");
db.update("Student", values, "name = ? ", new String[] {"XiaoMing"});

    6.其它操作

   
以下是关于数据库的其它操作,当中包含使用SQL语句运行,而查询数据Query方法因为涉及ListView显示,请见详细实例.

//关闭数据库
SQLiteDatabase.close();
//删除表 运行SQL语句
SQLiteDatabase.execSQL("DROP TABLE Student");
//删除数据库
this.deleteDatabase("StuDatabase.db");
//查询数据
SQLiteDatabase.query();

三. 数据库操作简单实例

   
显示效果例如以下图所看到的:

  

    首先。加入activity_main.xml文件布局例如以下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.touchimagetest.MainActivity"
tools:ignore="MergeRootFrame" >
<!-- 顶部 -->
<RelativeLayout
android:id="@+id/MyLayout_top"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_alignParentTop="true" >
<!-- 标题 -->
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textSize="20sp"
android:text="学号" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textSize="20sp"
android:text="姓名" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textSize="20sp"
android:text="电话" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textSize="20sp"
android:text="身高" />
</LinearLayout>
</RelativeLayout>
<!-- 底部按钮 -->
<RelativeLayout
android:id="@+id/MyLayout_bottom"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="90dp"
android:layout_alignParentBottom="true"
android:gravity="center">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:gravity="center" >
<EditText
android:id="@+id/edit_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textSize="20sp"
android:hint="学号" />
<EditText
android:id="@+id/edit_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textSize="20sp"
android:hint="姓名" />
<EditText
android:id="@+id/edit_tel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textSize="20sp"
android:hint="电话" />
<EditText
android:id="@+id/edit_height"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:textSize="20sp"
android:hint="身高" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="创表" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="插入" />
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="删除" />
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="更新" />
<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:text="查询" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
<!-- 显示列表 -->
<RelativeLayout
android:id="@+id/Content_Layout"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@id/MyLayout_bottom"
android:layout_below="@id/MyLayout_top"
android:background="#EFDFDF" >
<!-- 显示表内容 -->
<ListView
android:id="@+id/listview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center" >
</ListView>
</RelativeLayout>
</RelativeLayout>

   
然后是在res/layout中加入ListView显示的stu_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/stu_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="20sp" />
<TextView
android:id="@+id/stu_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="20sp" />
<TextView
android:id="@+id/stu_tel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="20sp" />
<TextView
android:id="@+id/stu_height"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="20sp" />
</LinearLayout>

   
再次,加入自己定义类MySQLiteOpenHelper:

//加入自己定义类 继承SQLiteOpenHelper
public class MySQLiteOpenHelper extends SQLiteOpenHelper { public Context mContext; //创建学生表(学号,姓名,电话,身高) 主键学号
public static final String createTableStu = "create table Student (" +
"id integer primary key, " +
"name text, " +
"tel text, " +
"height real)"; //抽象类 必须定义显示的构造函数 重写方法
public MySQLiteOpenHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
mContext = context;
} @Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
arg0.execSQL(createTableStu);
Toast.makeText(mContext, "Created", Toast.LENGTH_SHORT).show();
} @Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
arg0.execSQL("drop table if exists Student");
onCreate(arg0);
Toast.makeText(mContext, "Upgraged", Toast.LENGTH_SHORT).show();
}
}

   
最后是MainActivity.java文件,代码例如以下:

public class MainActivity extends Activity {

	//继承SQLiteOpenHelper类
private MySQLiteOpenHelper sqlHelper;
private ListView listview;
private EditText edit1;
private EditText edit2;
private EditText edit3;
private EditText edit4; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sqlHelper = new MySQLiteOpenHelper(this, "StuDatabase.db", null, 2);
//建立新表
Button createBn = (Button) findViewById(R.id.button1);
createBn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sqlHelper.getWritableDatabase();
}
});
//插入数据
Button insertBn = (Button) findViewById(R.id.button2);
edit1 = (EditText) findViewById(R.id.edit_id);
edit2 = (EditText) findViewById(R.id.edit_name);
edit3 = (EditText) findViewById(R.id.edit_tel);
edit4 = (EditText) findViewById(R.id.edit_height);
insertBn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = sqlHelper.getWritableDatabase();
ContentValues values = new ContentValues();
/*
//插入第一组数据
values.put("id", "10001");
values.put("name", "Eastmount");
values.put("tel", "15201610000");
values.put("height", "172.5");
db.insert("Student", null, values);
*/
values.put("id", edit1.getText().toString());
values.put("name", edit2.getText().toString());
values.put("tel", edit3.getText().toString());
values.put("height", edit4.getText().toString());
db.insert("Student", null, values);
Toast.makeText(MainActivity.this, "数据插入成功", Toast.LENGTH_SHORT).show();
edit1.setText("");
edit2.setText("");
edit3.setText("");
edit4.setText("");
}
});
//删除数据
Button deleteBn = (Button) findViewById(R.id.button3);
deleteBn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = sqlHelper.getWritableDatabase();
db.delete("Student", "height > ?", new String[] {"180"});
Toast.makeText(MainActivity.this, "删除数据", Toast.LENGTH_SHORT).show();
}
});
//更新数据
Button updateBn = (Button) findViewById(R.id.button4);
updateBn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase db = sqlHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("height", "180");
db.update("Student", values, "name = ?", new String[] {"XiaoMing"});
Toast.makeText(MainActivity.this, "更新数据", Toast.LENGTH_SHORT).show();
}
});
//查询数据
listview = (ListView) findViewById(R.id.listview1);
Button selectBn = (Button) findViewById(R.id.button5);
selectBn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
SQLiteDatabase db = sqlHelper.getWritableDatabase();
//游标查询每条数据
Cursor cursor = db.query("Student", null, null, null, null, null, null);
//定义list存储数据
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
//适配器SimpleAdapter数据绑定
//错误:构造函数SimpleAdapter没有定义 需把this改动为MainActivity.this
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, list, R.layout.stu_item,
new String[]{"id", "name", "tel", "height"},
new int[]{R.id.stu_id, R.id.stu_name, R.id.stu_tel, R.id.stu_height});
//读取数据 游标移动到下一行
while(cursor.moveToNext()) {
Map<String, Object> map = new HashMap<String, Object>();
map.put( "id", cursor.getString(cursor.getColumnIndex("id")) );
map.put( "name", cursor.getString(cursor.getColumnIndex("name")) );
map.put( "tel", cursor.getString(cursor.getColumnIndex("tel")) );
map.put( "height", cursor.getString(cursor.getColumnIndex("height")) );
list.add(map);
}
listview.setAdapter(adapter);
}
catch (Exception e){
Log.i("exception", e.toString());
}
}
});
}
}

    PS:希望文章对大家有所帮助,文章是关于SQLite的基础操作,并且没有涉及到数据库的触发器、存储过程、事务、索引等知识,网上也有非常多相关的资料.同一时候如今有门课程《数据库高级技术与开发》,故作者当个在线笔记及基础解说吧!这篇文章有一些不足之处,但作为基础文章还是不错的.

    下载地址:http://download.csdn.net/detail/eastmount/8159881

    主要參考:

    1.郭霖大神的《第一行代码Android》

    2.android中的数据库操作By:nieweilin

(By:Eastmount 2014-11-15 夜2点 http://blog.csdn.net/eastmount/)

[Android] SQLite数据库之增删改查基础操作的更多相关文章

  1. Android学习---数据库的增删改查(sqlite CRUD)

    上一篇文章介绍了sqlite数据库的创建,以及数据的访问,本文将主要介绍数据库的增删改查. 下面直接看代码: MyDBHelper.java(创建数据库,添加一列phone) package com. ...

  2. Android中Sqlite数据库进行增删改查

    今天这篇文章写Sqlite数据库,通过一个小案例来完整讲一下数据库常见的CRUD操作. 先对知识点总结: SQLite数据库 轻量级关系型数据库 创建数据库需要使用的api:SQLiteOpenHel ...

  3. greendao对SQLite数据库的增删改查操作

    利用greendao操作数据库时,都是以对象或者对象的list来进行增删改查的操作,操作的结果都是用一个list来接收的!!! 1.增加一条记录 Stu stu01=new Stu();stu01.s ...

  4. android 对sqlite数据库的增删改查等各种操作

    转载:http://blog.csdn.net/vrix/article/details/6717090 package com.sqlite.main; import java.io.File; i ...

  5. Android下利用SQLite数据库实现增删改查

    1: 首先介绍如何利用adb查看数据库 1: adb shell 2: cd /data/data/包名/databases 3:  sqlite3 数据库 4   接下来就可以进行数据库的sql语法 ...

  6. Android对Sqlite数据库的增删改查

    SqLite 数据库 Google 为我们提供了sqlite相关的api SqLiteOpenHelper 这是一个抽象的类 如果想要使用的话,需要其他的类去继承他 SqLiteDatabase 类 ...

  7. Android学习---SQLite数据库的增删改查和事务(transaction)调用

    上一篇文章中介绍了手工拼写sql语句进行数据库的CRUD操作,本文将介绍调用sqlite内置的方法实现CRUD操作,其实质也是通过拼写sql语句. 首先,创建一个新的android项目: 其次,查看代 ...

  8. SQLite数据库以及增删改查的案例

    Android使用开源的与操作系统无关的SQL数据库——SQLite 一:在命令行下创建数据库: 1.启动模拟器后,打开命令行,执行adb shell 2.进入所在工程目录 3.执行sqlite3 m ...

  9. 安卓 Android 简单数据库(增删改查)

    <Button android:id="@+id/delete_btn" android:layout_width="wrap_content" andr ...

随机推荐

  1. JavaScript Output

    JS can "display" data in different ways: (1)Writing into an alert box, using window.alert( ...

  2. CNN的发展

    模型的建立过程: 1959年,Hubel & Wiesel发现动物视觉皮层中的细胞负责检测感受野(receptive fields)中的光线.论文:Receptive fields and f ...

  3. Sqli-labs less 4

    Less-4 我们使用?id=1" 注入代码后,我们得到像这样的一个错误: You have an error in your SQL syntax; check the manual th ...

  4. POJ - 1835 宇航员(模拟题)

    问题描述: 宇航员在太空中迷失了方向,在他的起始位置现在建立一个虚拟xyz坐标系,称为绝对坐标系,宇航员正面的方向为x轴正方向,头顶方向为z轴正方向,则宇航员的初始状态如下图所示: 现对六个方向分别标 ...

  5. VB查询数据库之组合查询——机房收费总结(二)

    在机房收费系统中,组合查询用的还是挺多的,像上机状态查询窗体.学生上机统计信息窗体.操作员工记录窗体.基本信息维护窗体.这其中,学生基本信息维护窗体中的东西比较多,就以它为例子,说说组合查询吧! 学生 ...

  6. [BZOJ2337][HNOI2011]XOR和路径(概率+高斯消元)

    直接不容易算,考虑拆成位处理. 设f[i]表示i到n的期望路径异或和(仅考虑某一位),则$f[y]=\sum\limits_{exist\ x1\to y=0}\frac{f[x1]}{d[x1]}+ ...

  7. nginx和php-fpm的用户权限

    启动php-fpm sudo php-fpm -c /etc/php.ini [17-Sep-2018 00:36:59] ERROR: [pool www] please specify user ...

  8. WEB.NET error:请添加一个名为 jquery (区分大小写)的 ScriptResourceMapping 解决方案

    参考 http://blog.csdn.net/kisscatforever/article/details/50579935 今天用了一个组件 一个验证型的组件. 然后出现了这个问题. 我看了网上一 ...

  9. 模仿.Net ThreadPool的线程池控件

    http://www.2ccc.com/btdown.asp?articleid=5953 ftp://download:S3cirpYW3DoR@www.2ccc.com/vcl/system/20 ...

  10. 从co到koa01-co

    thunk 他的发展是由函数的求值策略的分歧决定的,两种求值策略 传值调用,在进入函数体之前就直接执行完,把值传进去 传名调用,将表达式传入函数体,只在用到他的时候求值 传名函数的编译器实现,其实就是 ...