Android自带 SQLite数据库

来源:互联网 发布:网络建设方案ppt 编辑:程序博客网 时间:2024/05/19 03:26

当我们需要存储大量数据的时候就需要数据库,Android自带了一种轻量级数据库SQLite。SQLite甚至不需要安装和启动服务进程,它只是一个后缀为.db的数据库文件,但它支持SQL语句。

关于SQLite的使用需要一个SQLiteDataBase类,该类底层就是一个数据库文件,一个该类代表一个数据库,对数据库的操作也要通过SQLiteDataBase类。

 

SQLiteDatabase提供如下静态方法来打开一个对应的数据库文件:

  openDatabase(String path,SQLiteDatabase.CursorFactory,int)

   打开path文件所代表的SQLite数据库

  openOrCreateDatabase(String path,SQLiteDatabase.CursorFactory)

   打开或者创建path文件所代表的SQLite数据库

  openOrCreateDatabase(File file,SQLiteDatabase.CursorFactory)

   打开或者创建file文件所代表的SQLite数据库

 

执行SQL的语句如下

execSQL(String sql,Object[] bindArgs)

execSQL(String sql)

执行增加、删除、更新等没有返回值的SQL语句,第一种第二个参数为SQL语句中可包含的占位符

Cursor rawQuery(String,String[])

执行查询语句,返回Cursor

Cursor即如SQL中的resultSet,是一个结果集,我们这里将使用SimpleCursorAdapter这个适配器配置ListView,其中可直接使用该结果集。

 

使用完毕后需要调用SQLiteDataBase.close()方法关闭数据库。

 

SQLite内部只支持5种数据类型,但实际上SQLite完全可以接受varchar,char等数据类型,只不过SQLite会在运算或保存时将他们转换成下面的五种数据类型中相应的类型:

NULL: 空值

INTEGER: 整数,依据值的大小可以依次被存储为1,2,3,4,5,6,7,8个字节

REAL: 浮动的数值,被存储为8字节的IEEE浮动标记序号.

TEXT: 文本字符串,使用数据库编码存储(TUTF-8,UTF-16BE or UTF-16-LE).

BLOB: BLOB数据,如何输入就如何存储,不改变格式.

除此之外,SQLite还有一个特点:允许把各种类型的数据保存到任何类型字段中,开发者可以不用关心申明该字段所使用的数据类型。例如程序可以把字符串类型的值存入INTEGER类型的字段中,也可以吧数值类型的值存储到布尔类型中。

但有一种情况例外:定义INTEGERPRIMARY KEY的字段只能存储64位整数(主键)。

 

由于SQLite允许存入数据时忽略底层数据列实际的数据类型,因此在编写建表语句时可以省略数据列后面的类型声明。但实际上,sqlite3也接受如下的数据类型:

smallint 16位的整数。

interger 32位的整数。

decimal(p,s) 精确值p是指全部有几个十进制数,s是指小数点后可以有几位小数。如果没有特别指定,则系统会默认为p=5s=0 。

float 32位元的实数。

double 64位元的实数。

char(n) n 长度的字串,n不能超过 254。

varchar(n) 长度不固定且其最大长度为 n 的字串,n不能超过 4000。

graphic(n) 和 char(n) 一样,不过其单位是两个字节, n不能超过127。这个形态是为了支持两个字节长度的字体,如中文字。

vargraphic(n) 可变长度且其最大长度为n的双字元字串,n不能超过2000

date 包含了 年份、月份、日期。

time 包含了 小时、分钟、秒。

timestamp 包含了年、月、日、时、分、秒、千分之一秒

 

同时在Android SDK中提供了一个sqlite3工具,供我们对Android中的数据库文件进行操作,但需要将手机或模拟机中的数据库导出到电脑,在电脑终端使用。

大概可以这般使用(文件位置为data/data/包名/files/xxx.db)

 

 

以下我们使用SQLite对用户名和密码的增删改查做一个简单的实现。首先我们通过文本输入框输入信息,建表然后保存,再以列表的形式显示保存好的内容,实现点击更行、长按删除。

布局文件如下

[html] view plain copy
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical"  
  6.     android:paddingBottom="@dimen/activity_vertical_margin"  
  7.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  8.     android:paddingRight="@dimen/activity_horizontal_margin"  
  9.     android:paddingTop="@dimen/activity_vertical_margin"  
  10.     tools:context="com.briup.sqlite.MainActivity" >  
  11.   
  12.     <EditText  
  13.         android:id="@+id/username"  
  14.         android:layout_width="match_parent"  
  15.         android:layout_height="wrap_content"  
  16.         android:hint="User name" />  
  17.   
  18.     <EditText  
  19.         android:id="@+id/userpwd"  
  20.         android:layout_width="match_parent"  
  21.         android:layout_height="wrap_content"  
  22.         android:hint="Password" />  
  23.   
  24.     <Button  
  25.         android:layout_width="match_parent"  
  26.         android:layout_height="wrap_content"  
  27.         android:onClick="save"  
  28.         android:text="SAVE" />  
  29.   
  30.     <Button  
  31.         android:layout_width="match_parent"  
  32.         android:layout_height="wrap_content"  
  33.         android:onClick="read"  
  34.         android:text="READ" />  
  35.   
  36.     <ListView  
  37.         android:id="@+id/values_list"  
  38.         android:layout_width="match_parent"  
  39.         android:layout_height="wrap_content" />  
  40.   
  41. </LinearLayout>  

values_item.xml文件如下

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="horizontal" >  
  6.   
  7.     <TextView  
  8.         android:id="@+id/tv_id"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:textSize="20sp"  
  12.         android:visibility="gone" />  
  13.   
  14.     <TextView  
  15.         android:id="@+id/tv_username"  
  16.         android:layout_width="wrap_content"  
  17.         android:layout_height="wrap_content"  
  18.         android:layout_marginLeft="10dp"  
  19.         android:textSize="20sp" />  
  20.   
  21.     <TextView  
  22.         android:id="@+id/tv_password"  
  23.         android:layout_width="wrap_content"  
  24.         android:layout_height="wrap_content"  
  25.         android:layout_marginLeft="20dp"  
  26.         android:textSize="20sp" />  
  27.   
  28. </LinearLayout>  

alertdialog.xml文件如下

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <LinearLayout  
  8.         android:layout_width="match_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:orientation="horizontal" >  
  11.   
  12.         <TextView  
  13.             android:layout_width="wrap_content"  
  14.             android:layout_height="wrap_content"  
  15.             android:text="姓名" />  
  16.   
  17.         <EditText  
  18.             android:id="@+id/alert_name"  
  19.             android:layout_width="match_parent"  
  20.             android:layout_height="wrap_content" />  
  21.     </LinearLayout>  
  22.   
  23.     <LinearLayout  
  24.         android:layout_width="match_parent"  
  25.         android:layout_height="wrap_content"  
  26.         android:orientation="horizontal" >  
  27.   
  28.         <TextView  
  29.             android:layout_width="wrap_content"  
  30.             android:layout_height="wrap_content"  
  31.             android:text="密码" />  
  32.   
  33.         <EditText  
  34.             android:id="@+id/alert_pass"  
  35.             android:layout_width="match_parent"  
  36.             android:layout_height="wrap_content" />  
  37.     </LinearLayout>  
  38.   
  39. </LinearLayout>  

MainActivity类文件如下

[java] view plain copy
  1. import android.app.Activity;  
  2. import android.app.AlertDialog;  
  3. import android.app.AlertDialog.Builder;  
  4. import android.content.DialogInterface;  
  5. import android.content.DialogInterface.OnClickListener;  
  6. import android.database.Cursor;  
  7. import android.database.sqlite.SQLiteDatabase;  
  8. import android.os.Bundle;  
  9. import android.view.View;  
  10. import android.widget.AdapterView;  
  11. import android.widget.AdapterView.OnItemClickListener;  
  12. import android.widget.AdapterView.OnItemLongClickListener;  
  13. import android.widget.EditText;  
  14. import android.widget.ListView;  
  15. import android.widget.SimpleCursorAdapter;  
  16. import android.widget.TextView;  
  17. import android.widget.Toast;  
  18.   
  19. public class MainActivity extends Activity {  
  20.     private EditText username, password;  
  21.     private SQLiteDatabase DB;  
  22.   
  23.     private ListView values;  
  24.   
  25.     @Override  
  26.     protected void onCreate(Bundle savedInstanceState) {  
  27.         super.onCreate(savedInstanceState);  
  28.         setContentView(R.layout.activity_main);  
  29.         username = (EditText) findViewById(R.id.username);  
  30.         password = (EditText) findViewById(R.id.userpwd);  
  31.         values = (ListView) findViewById(R.id.values_list);  
  32.         // 获取SQLiteDatabase以操作SQL语句  
  33.         DB = SQLiteDatabase.openOrCreateDatabase(getFilesDir() + "/info.db",  
  34.                 null);  
  35.         // 长按删除  
  36.         values.setOnItemLongClickListener(new OnItemLongClickListener() {  
  37.   
  38.             @Override  
  39.             public boolean onItemLongClick(AdapterView<?> arg0, View arg1,  
  40.                     int arg2, long arg3) {  
  41.                 // 获取所点击项的_id  
  42.                 TextView tv = (TextView) arg1.findViewById(R.id.tv_id);  
  43.                 final String id = tv.getText().toString();  
  44.                 // 通过Dialog提示是否删除  
  45.                 AlertDialog.Builder builder = new AlertDialog.Builder(  
  46.                         MainActivity.this);  
  47.                 builder.setMessage("确定要删除吗?");  
  48.                 // 确定按钮点击事件  
  49.                 builder.setPositiveButton("确定"new OnClickListener() {  
  50.   
  51.                     @Override  
  52.                     public void onClick(DialogInterface dialog, int which) {  
  53.                         delete(id);  
  54.                         replaceList();// 删除后刷新列表  
  55.                     }  
  56.                 });  
  57.                 // 取消按钮点击事件  
  58.                 builder.setNegativeButton("取消"new OnClickListener() {  
  59.   
  60.                     @Override  
  61.                     public void onClick(DialogInterface dialog, int which) {  
  62.                         dialog.dismiss();  
  63.                     }  
  64.                 });  
  65.                 builder.create().show();  
  66.   
  67.                 return true;  
  68.             }  
  69.         });  
  70.         // 点击更新  
  71.         values.setOnItemClickListener(new OnItemClickListener() {  
  72.   
  73.             @Override  
  74.             public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
  75.                     long arg3) {  
  76.                 // 获取_id,username,password项  
  77.                 TextView tvId = (TextView) arg1.findViewById(R.id.tv_id);  
  78.                 TextView tvName = (TextView) arg1  
  79.                         .findViewById(R.id.tv_username);  
  80.                 TextView tvPass = (TextView) arg1  
  81.                         .findViewById(R.id.tv_password);  
  82.                 final String id = tvId.getText().toString();  
  83.                 String username = tvName.getText().toString();  
  84.                 String password = tvPass.getText().toString();  
  85.                 // 通过Dialog弹出修改界面  
  86.                 AlertDialog.Builder builder = new Builder(MainActivity.this);  
  87.                 builder.setTitle("修改");  
  88.                 // 自定义界面包括两个文本输入框  
  89.                 View v = View.inflate(MainActivity.this, R.layout.alertdialog,  
  90.                         null);  
  91.                 final EditText etName = (EditText) v  
  92.                         .findViewById(R.id.alert_name);  
  93.                 final EditText etPass = (EditText) v  
  94.                         .findViewById(R.id.alert_pass);  
  95.                 // Dialog弹出就显示原内容  
  96.                 etName.setText(username);  
  97.                 etPass.setText(password);  
  98.   
  99.                 builder.setView(v);  
  100.                 // 确定按钮点击事件  
  101.                 builder.setPositiveButton("保存"new OnClickListener() {  
  102.   
  103.                     @Override  
  104.                     public void onClick(DialogInterface dialog, int which) {  
  105.                         String newName = etName.getText().toString();  
  106.                         String newPass = etPass.getText().toString();  
  107.                         updata(newName, newPass, id);  
  108.                         replaceList();// 更新后刷新列表  
  109.                     }  
  110.                 });  
  111.                 // 取消按钮点击事件  
  112.                 builder.setNegativeButton("取消"new OnClickListener() {  
  113.   
  114.                     @Override  
  115.                     public void onClick(DialogInterface dialog, int which) {  
  116.                         dialog.dismiss();  
  117.                     }  
  118.                 });  
  119.                 builder.create().show();  
  120.             }  
  121.         });  
  122.     }  
  123.   
  124.     /** 
  125.      * 关闭程序关闭数据库 
  126.      */  
  127.     @Override  
  128.     protected void onDestroy() {  
  129.         super.onDestroy();  
  130.         DB.close();  
  131.     }  
  132.   
  133.     /** 
  134.      * 保存按钮点击事件,首次插入由于没有表必然报错,简化程序利用try-catch在catch中创建表 
  135.      */  
  136.     public void save(View v) {  
  137.         String name = username.getText().toString();  
  138.         String pass = password.getText().toString();  
  139.         try {  
  140.             insert(name, pass);  
  141.         } catch (Exception e) {  
  142.             create();  
  143.             insert(name, pass);  
  144.         }  
  145.         Toast.makeText(this"Save Success", Toast.LENGTH_SHORT).show();  
  146.         username.setText("");  
  147.         password.setText("");  
  148.     }  
  149.   
  150.     /** 
  151.      * 读取按钮点击事件,以列表的形式显示所有内容 
  152.      */  
  153.     public void read(View v) {  
  154.         replaceList();  
  155.     }  
  156.   
  157.     /** 
  158.      * ListView的适配器 
  159.      */  
  160.     public void replaceList() {  
  161.         Cursor cursor = select();  
  162.         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,  
  163.                 R.layout.values_item, cursor, new String[] { "_id""username",  
  164.                         "password" }, new int[] { R.id.tv_id, R.id.tv_username,  
  165.                         R.id.tv_password },  
  166.                 SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);  
  167.         values.setAdapter(adapter);  
  168.     }  
  169.   
  170.     /** 
  171.      * 建表 
  172.      */  
  173.     public void create() {  
  174.         String createSql = "create table user(_id integer primary key autoincrement,username,password)";  
  175.         DB.execSQL(createSql);  
  176.     }  
  177.   
  178.     /** 
  179.      * 插入 
  180.      */  
  181.     public void insert(String username, String password) {  
  182.         String insertSql = "insert into user(username,password) values(?,?)";  
  183.         DB.execSQL(insertSql, new String[] { username, password });  
  184.     }  
  185.   
  186.     /** 
  187.      * 查询 
  188.      */  
  189.     public Cursor select() {  
  190.         String selectSql = "select _id,username,password from user";  
  191.         Cursor cursor = DB.rawQuery(selectSql, null);// 我们需要查处所有项故不需要查询条件  
  192.         return cursor;  
  193.     }  
  194.   
  195.     /** 
  196.      * 删除 
  197.      */  
  198.     public void delete(String id) {  
  199.         String deleteSql = "delete from user where _id=?";  
  200.         DB.execSQL(deleteSql, new String[] { id });  
  201.     }  
  202.   
  203.     /** 
  204.      * 更新 
  205.      */  
  206.     public void updata(String username, String password, String id) {  
  207.         String updataSql = "update user set username=?,password=? where _id=?";  
  208.         DB.execSQL(updataSql, new String[] { username, password, id });  
  209.     }  
  210. }  

效果如下

 

阅读全文
0 0
原创粉丝点击