SQLite简单使用

sqlite作为轻量型数据库,也就是一个.db文件,使用起来非常方便。下面简单介绍下数据库常用的增删改查操作。

首先布局文件:

[java] view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <!--?xml version="1.0" encoding="utf-8"?>  
  2. <linearlayout xmlns:android="http://schemas.android.com/apk/res/android"</linearlayout xmlns:android=  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical" >  
  6.       
  7.    <button    </button   <>
  8.        android:layout_width="match_parent"  
  9.        android:layout_height="wrap_content"  
  10.        android:id="@+id/createdatabase"  
  11.        android:text="创建数据库" />  
  12.      
  13.     <button    </button   <>
  14.        android:layout_width="match_parent"  
  15.        android:layout_height="wrap_content"  
  16.        android:id="@+id/insert"  
  17.        android:text="插入数据" />  
  18.     
  19.     <button    </button   <>
  20.        android:layout_width="match_parent"  
  21.        android:layout_height="wrap_content"  
  22.        android:id="@+id/query"  
  23.        android:text="查询并显示数据" />  
  24.     <button    </button   <>
  25.        android:layout_width="match_parent"  
  26.        android:layout_height="wrap_content"  
  27.        android:id="@+id/update"  
  28.        android:text="更新数据" />  
  29.     <button    </button   <>
  30.         android:layout_width="match_parent"  
  31.         android:layout_height="wrap_content"  
  32.         android:id="@+id/delete"  
  33.         android:text="删除数据" />  
  34.        <textview    </textview   <>
  35.         android:id="@+id/text"  
  36.         android:layout_width="wrap_content"  
  37.         android:layout_height="30dp"  
  38.         android:text="显示数据" />  
  39.   
效果:





借助SQLiteOpenHelper创建数据库,创建了一张表worker(id,name,adress),可以指定id为主键:id integer primary key,还可以指定自动增长,再加上autoincrement就行了。简单的说明下sqlite中常用数据类型,integer表示整型,text表示文本类型,real表示浮点型,blob表示二进制类型。


[java] view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. public class myDatabaseAdapter extends SQLiteOpenHelper{  
  2.       
  3.     private final String CREATE_TABLE_A = "create table worker(" + "id integer," + "name text," + "adress text)";  
  4.     public myDatabaseAdapter(Context context, String name,CursorFactory factory, int version) {  
  5.         super(context, name,factory, version);  
  6.         // TODO 自动生成的构造函数存根  
  7.     }  
  8.   
  9.     @Override  
  10.     public void onCreate(SQLiteDatabase db) {  
  11.         // TODO 自动生成的方法存根  
  12.         db.execSQL(CREATE_TABLE_A);  
  13.     }  
  14.     @Override  
  15.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  16.         // TODO 自动生成的方法存根  
  17.           
  18.     }  
  19. }  
MainActivity.java:
[java] view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. public class MainActivity extends Activity implements OnClickListener{  
  2.       
  3.     private String DB_NAME = "lios";  
  4.     private Button buttoncreate;  
  5.     private Button insert;  
  6.     private Button query;  
  7.     private Button update;  
  8.     private Button delete;  
  9.     private TextView text;  
  10.     private SQLiteDatabase db;  
  11.     private myDatabaseAdapter dbHelper;  
  12.       
  13.     @Override  
  14.     protected void onCreate(Bundle savedInstanceState) {  
  15.         super.onCreate(savedInstanceState);  
  16.         setContentView(R.layout.activity_main);  
  17.           
  18.         buttoncreate = (Button)findViewById(R.id.createdatabase);  
  19.         insert = (Button)findViewById(R.id.insert);  
  20.         query = (Button)findViewById(R.id.query);  
  21.         update = (Button)findViewById(R.id.update);  
  22.         delete = (Button)findViewById(R.id.delete);  
  23.         text = (TextView)findViewById(R.id.text);  
  24.             dbHelper= new myDatabaseAdapter(this,DB_NAME,null,1);  
  25.         buttoncreate.setOnClickListener(this);  
  26.         insert.setOnClickListener(this);  
  27.         query.setOnClickListener(this);  
  28.         update.setOnClickListener(this);  
  29.         delete.setOnClickListener(this);  
  30.           
  31.     }  
  32.             public void onClick(View v) {  
  33.                 // TODO 自动生成的方法存根  
  34.                 switch (v.getId()) {  
  35.                 case R.id.createdatabase:  
  36.                   
  37.                     db = dbHelper.getWritableDatabase();  
  38.                       break;  
  39.                 case R.id.insert:  
  40.                     SQLiteDatabase db1 = dbHelper.getWritableDatabase();  
  41.                     db1.execSQL("insert into worker (id,name,adress) values (?,?,?)",new String[]{"1","w","shanghai"});  
  42.                     /*  ContentValues values = new ContentValues(); 
  43.                     values.put("id",1); 
  44.                     values.put("name","w"); 
  45.                     values.put("adress", "shanghai"); 
  46.                     db1.insert("worker",null, values); 
  47.                     values.clear(); 
  48.                     values.put("id",3); 
  49.                     values.put("name","d"); 
  50.                     values.put("adress", "shanghai"); 
  51.                     db1.insert("worker",null, values);*/  
  52.                     break;  
  53.                 case R.id.query:  
  54.                     SQLiteDatabase db2 = dbHelper.getWritableDatabase();  
  55.                     Cursor cursor = db2.rawQuery("select * from worker",null);  
  56.                      if(cursor.moveToFirst()){  
  57.                         int id = cursor.getInt(cursor.getColumnIndex("id"));  
  58.                     String name = cursor.getString(cursor.getColumnIndex("name"));  
  59.                     Log.d("name",name);  
  60.                     String adress = cursor.getString(cursor.getColumnIndex("adress"));  
  61.                     text.setText(id+name+adress);  
  62.                     }  
  63.                     cursor.close();       //关闭游标  
  64.                       break;  
  65.                 case R.id.update:  
  66.                     SQLiteDatabase db3 = dbHelper.getWritableDatabase();  
  67.                     db3.execSQL("update worker set id =? where name =?",new String[]{"5","w"});  
  68.                     Toast.makeText(this,"数据已更改",Toast.LENGTH_SHORT).show();;  
  69.                       break;  
  70.                 case R.id.delete:  
  71.                     SQLiteDatabase db4 = dbHelper.getWritableDatabase();  
  72.                     db4.execSQL("delete from worker where adress = ?",new String[]{"beijing"});  
  73.                     break;  
  74.                 default:  
  75.                     break;  
  76.                 }  
  77.                   
  78.                   
  79.             }  
  80.               
  81.             public void onDestory(){  
  82.                   
  83.                 db.close();  
  84.             }  
  85.   
  86.        }  
简单的分析上面代码,由于自己喜欢写sql语句,所以上面就直接写sql语句了,也可以用sqlite提供的方法进行操作。注意我们进行CRUD操作,都是借助 SQLiteDatabase对象来进行操作,而SQLiteOpenHelper抽象类中有方法getWritableDatabase()可以获得SQLiteDatabase对象:
[java] view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. <pre name=SQLiteDatabase getWritableDatabase() {  </pre name=<>
  2.         synchronized (this) {  
  3.             return getDatabaseLocked(true);  
  4.         }  
  5.     }  
 
 

或者用

SQLiteOpenHelper抽象类中getReadableDatabase()方法来获取:

[java] view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. public SQLiteDatabase getReadableDatabase() {  
  2.       synchronized (this) {  
  3.           return getDatabaseLocked(false);  
  4.       }  
  5.   }  
为了看的更清楚,给出getDatabaseLocked()函数部分,详细请阅读源码。

[java] view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. private SQLiteDatabase getDatabaseLocked(boolean writable) {  
  2.        if (mDatabase != null) {  
  3.            if (!mDatabase.isOpen()) {  
  4.                // Darn!  The user closed the database by calling mDatabase.close().  
  5.                mDatabase = null;  
  6.            } else if (!writable || !mDatabase.isReadOnly()) {  
  7.                // The database is already open for business.  
  8.                return mDatabase;  
  9.            }  
  10.        }  
  11.     .....  
  12.     .....  

其中getWritableDatabase() 方法以读写方式打开数据库,一旦数据库的磁盘空间满了,数据库就只能读而不能写,倘若使用的是getWritableDatabase() 方法就会出错。
而getReadableDatabase()方法则是先以读写方式打开数据库,如果数据库的磁盘空间满了,就会打开失败,当打开失败后会继续尝试以只读方式打开数据库。如果该问题成功解决,则只读数据库对象就会关闭,然后返回一个可读写的数据库对象。


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29876893/viewspace-2075095/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/29876893/viewspace-2075095/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值