android下创建数据库的步骤 增删改查 和 测试程序的方法流程

android下创建数据库的步骤:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1.   
1.创建一个数据库打开的帮助类  继承SQLiteOpenHelper
2. 构造方法 设置数据库文件的名称  设置游标工厂 null  数据库的版本 1
3. 填写 onCreate()方法  数据库表结构的初始化  数据库第一次被创建的时候 调用的方法

4. helper.getReadabledatabase() 或者调用helper.getWriteabledatabase() 获取数据库的示例

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.example.note.db;  
  2.   
  3. import android.content.Context;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5. import android.database.sqlite.SQLiteDatabase.CursorFactory;  
  6. import android.database.sqlite.SQLiteOpenHelper;  
  7.   
  8. public class NoteSQLiteOpenHelper extends SQLiteOpenHelper {  
  9.   
  10.     /** 
  11.      * @param context 上下文 ; 
  12.      * @param name 数据库的名称 
  13.      *  
  14.      * @param cursorfactory 游标工厂null为默认的,是从第一条开始查询  
  15.      *  
  16.      * @param version 数据库的版本号从1开始。 
  17.      */  
  18.   
  19.     public NoteSQLiteOpenHelper(Context context) {  
  20.           
  21.         super(context, "note123.db"null1);  
  22.         // TODO Auto-generated constructor stub  
  23.     }  
  24.   
  25.     /** 
  26.      *oncreate 方法会在数据库第一次创建的时候被调用 适合做数据库表结构的初始化  
  27.      * 
  28.      */  
  29.       
  30.     public void onCreate(SQLiteDatabase db) {  
  31.         // TODO Auto-generated method stub  
  32.         //db.execSQL("create table account (id integer primary key autoincrement , name  varchar(20), money varchar(20) )");  
  33.         db.execSQL("create table account (id integer primary key autoincrement , " +  
  34. <span style="white-space:pre">              </span>"name  varchar(20), money varchar(20) )");//执行sql语句,可以建立表 varchar() 代表String类型  
  35.           
  36.           
  37.           
  38.   
  39.     }  
  40.   
  41.     @Override  
  42.     public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {  
  43.         System.out.println("更新了");//当数据库有变化的时候会打印这条内容。没变化是不会打印这条内容的。  
  44.     }  
  45.   
  46. }  

execSql()中的数据建立方法不多出了。。建立了 id  ,name,  money三个列

其中要继承SQLiteOpenHelper的方法为

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public NoteSQLiteOpenHelper(Context context, String name,CursorFactory factory, int version) {  
  2.         super(context, name, factory, version);  
  3.         // TODO Auto-generated constructor stub  
  4.     }  
只是演示,也为了调用方便只保留了Context的参数。其他参数都在super()中可以自动改变。如果有许多数据库。可以不删除元素 动态的添加 数据库的名字版本等。。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. NoteSQLiteOpenHelper helper=new NoteSQLiteOpenHelper(this.getContext());//实例化要测试的数据     要测试所以要有上下文  
  2. //注意:只有执行了getWritableDatabase 或者getreadabledatabase() 数据库才会被创建  
  3. helper.getWritableDatabase();  

这样就可以建立数据库了。上面的第一句只能在测试中这么使用      如果在增删改查的时候要这么写

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1.     //因为任何一个操作都需要得到NoteSQLiteOpenHelper helper  
  2.     //把他放在构造方法里面初始化  
  3.     private NoteSQLiteOpenHelper helper;  
  4.       
  5.     public NoteDao(Context context) { //在构造方法里面就进行初始化   
  6.         helper=new NoteSQLiteOpenHelper (context);  
  7.     }<pre code_snippet_id="333603" snippet_file_name="blog_20140508_4_4893577" name="code" class="java">helper.getWritableDatabase();   //每个增删改查只写这一句就可以了,减少代码复用 </pre><pre code_snippet_id="333603" snippet_file_name="blog_20140508_4_4893577" name="code" class="java"></pre>  
  8. <pre></pre>  


接下来建立一个测试类。。
1。继承AndroidTestCase 
2。.更改 AndroidManifest.xml 的内容
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.example.note.test;  
  2.   
  3. import com.example.note.db.NoteSQLiteOpenHelper;  
  4.   
  5. import android.test.AndroidTestCase;  
  6.   
  7. public class TestNoteOpenHelper extends AndroidTestCase {  
  8.   
  9.     public void testCreateDB() throws Exception{  
  10.         //要测试所以要有上下文  getContext 是获取到测试框架的一个虚拟的模拟的假的上下文  
  11.         NoteSQLiteOpenHelper helper=new NoteSQLiteOpenHelper(this.getContext());//实例化要测试的数据     要测试所以要有上下文  
  12.         //注意:只有执行了getWritableDatabase 或者getreadabledatabase() 数据库才会被创建  
  13.         helper.getWritableDatabase();  
  14. //      helper.getReadableDatabase();  
  15.       
  16.     }  
  17. }  

AndroidManifest.xml 加入的内容为
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <instrumentation  
  2.         android:name="android.test.InstrumentationTestRunner"  
  3.         android:targetPackage="com.example.note" />  
  4.  <uses-library android:name="android.test.runner" />  

这两句其中 com.example.note 为要测试的包名
具体内容是
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.note"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="17" />  
  10.   <instrumentation  
  11.         android:name="android.test.InstrumentationTestRunner"  
  12.         android:targetPackage="com.example.note" />  
  13.       
  14.     <application  
  15.         android:allowBackup="true"  
  16.         android:icon="@drawable/ic_launcher"  
  17.         android:label="@string/app_name"  
  18.         android:theme="@style/AppTheme" >  
  19.         <uses-library android:name="android.test.runner" />  
  20.         <activity  
  21.             android:name="com.example.note.MainActivity"  
  22.             android:label="@string/app_name" >  
  23.               
  24.             <intent-filter>  
  25.                 <action android:name="android.intent.action.MAIN" />  
  26.   
  27.                 <category android:name="android.intent.category.LAUNCHER" />  
  28.             </intent-filter>  
  29.         </activity>  
  30.     </application>  
  31.   
  32. </manifest>  

这两句如果记不住该咋办呢。
在File------ new---project---android---Android Test Project---next
-- 随便输入一个名字--next--- 选择 An existing Android project 选项 选择一个要测试的那个文件 ---  Finish


会创建一个工程。。它里面的AndroidManifest.xml  就有我们想要的那两段代码。


接着上面的代码开始增删改查:
先要建立一个bean文件。。包含所有要增删改查的数据。。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.example.note.domain;  
  2.   
  3. public class NoteBean {  
  4.     private int id;  
  5.     private float money;  
  6.     private String name;  
  7.       
  8.     public int getId() {  
  9.         return id;  
  10.     }  
  11.     public void setId(int id) {  
  12.         this.id = id;  
  13.     }  
  14.     public float getMoney() {  
  15.         return money;  
  16.     }  
  17.     public void setMoney(float money) {  
  18.         this.money = money;  
  19.     }  
  20.     public String getName() {  
  21.         return name;  
  22.     }  
  23.     public void setName(String name) {  
  24.         this.name = name;  
  25.     }  
  26.     public NoteBean(int id, float money, String name) {  //用于批量给三个变量复制。。  
  27.         super();  
  28.         this.id = id;  
  29.         this.money = money;  
  30.         this.name = name;  
  31.     }  
  32.     public NoteBean(){}  
  33.     @Override  
  34.     public String toString() {  
  35.         return "NoteBean [id=" + id + ", money=" + money + ", name=" + name  
  36.                 + "]";  
  37.     }  
  38.       
  39.       
  40. }  

增删改查。。属于最简单的
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.example.note.db.dao;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import android.content.Context;  
  7. import android.database.Cursor;  
  8. import android.database.sqlite.SQLiteDatabase;  
  9.   
  10. import com.example.note.db.NoteSQLiteOpenHelper;  
  11. import com.example.note.domain.NoteBean;  
  12.   
  13.   
  14. /** 
  15.  *记账本的dao 
  16.  *@author Administrator  
  17.  */  
  18.    
  19. public class NoteDao {  
  20.       
  21.     //因为任何一个操作都需要得到NoteSQLiteOpenHelper helper  
  22.     //把他放在构造方法里面初始化  
  23.     private NoteSQLiteOpenHelper helper;  
  24.       
  25.     public NoteDao(Context context) { //在构造方法里面就进行初始化   
  26.         helper=new NoteSQLiteOpenHelper (context);  
  27.     }  
  28.   
  29.     /** 
  30.      *添加一条账目信息到数据库 
  31.      *@param name 花销名称 
  32.      *@param 金额 
  33.      */  
  34.     public void add (String name,float money){  
  35.         //NoteSQLiteOpenHelper helper=new NoteSQLiteOpenHelper();  
  36.         SQLiteDatabase db=helper.getWritableDatabase();  
  37.         db.execSQL("insert into account(name,money) values(?,?)",  
  38.                 new Object[]{name,money});  
  39.         //记住;关闭数据库---否则打开过多数据库会导致数据库无法使用  
  40.         db.close();  
  41.     }  
  42.     public void delete(int id){  
  43.         SQLiteDatabase db=helper.getWritableDatabase();  
  44.         db.execSQL("delete from account where id=?"new Object[]{id});  
  45.         db.close();  
  46.     }  
  47.       
  48.     public void update(int id,float newMoney){  
  49.         SQLiteDatabase db=helper.getWritableDatabase();  
  50.         db.execSQL("update account set money=? where id=?"new Object[]{newMoney,id});  
  51.     }  
  52.     /** 
  53.      *返回数据库中所有的内容  
  54.      */  
  55.        
  56.        
  57.     public List<NoteBean> findAll(){  
  58.         SQLiteDatabase db=helper.getWritableDatabase();  
  59.         List<NoteBean> noteBeans=new ArrayList<NoteBean>();  
  60.         //获取到数据库查询的结果游标  
  61.         Cursor cursor =db.rawQuery("select * from account",   
  62.                 null);  
  63.           
  64.         //cursor.moveToPosition(arg0);// 直接定位到查询的哪一位  
  65.         while(cursor.moveToNext()){//向下查询  
  66. //          int id=cursor.getInt(0);//得到第几列的内容  
  67. //          String name= cursor.getString(2);  
  68. //          float money=cursor.getFloat(1);     
  69.             //这样貌似容易搞混。如果一百个那绝对蒙了  
  70.             int id=cursor.getInt(cursor.getColumnIndex("id"));  
  71.             String name= cursor.getString(cursor.getColumnIndex("name"));  
  72.             float money=cursor.getFloat(cursor.getColumnIndex("money"));   
  73.             NoteBean bean=new NoteBean(id,money,name); //把三个数传到NoteBean中。这样就可以调用了  
  74.             noteBeans.add(bean);//把bean中的数据存到list集合中  
  75.             bean=null;//节省内存  
  76.         }  
  77.         db.close();  
  78.         return noteBeans;  
  79.       
  80.     }  
  81.       
  82. }  

其中。db.rawQuery() 是有返回值的。。类型是Cursor类型。。可以用于操作得到的数据。。
db.exeSQL().没有返回值 感觉就是用于对数据库进行操作。。
有人会疑惑  rawQuery()可以代替exeSQL()么? 只让rawQuery()对数据操作不使用返回值。。我测试了。是不可以的。。根本跑不通
比如:Cursor cusor = db.rawQuery("delete from account where id=?", (String[]) new Object[]{id});  会报错的。。


继续。建立一个测试类。测试增删改查是否有用。。
[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.example.note.test;  
  2.   
  3. import java.util.List;  
  4.   
  5. import com.example.note.db.dao.NoteDao;  
  6. import com.example.note.domain.NoteBean;  
  7.   
  8. import android.test.AndroidTestCase;  
  9. import android.widget.Toast;  
  10.   
  11. public class TestNoteDao extends AndroidTestCase {  
  12.     //增加  
  13.     public void testAdd() throws Exception {  
  14.         NoteDao dao = new NoteDao(getContext());  
  15.   
  16.         for (int i = 0; i < 20; i++) {  
  17.             dao.add("3月" + i + "号打酱油"3.10f + i);  
  18.   
  19.         }  
  20.   
  21.     }  
  22.     //更新  
  23.     public void testupdate() throws Exception {  
  24.         NoteDao dao = new NoteDao(getContext());  
  25.         dao.update(29.88f);  
  26.     }  
  27.     //删除  
  28.     public void testDelete() throws Exception {  
  29.         NoteDao dao = new NoteDao(getContext());  
  30.         dao.delete(4);  
  31.     }  
  32.     //查找  
  33.     public void testFindAll() throws Exception {  
  34.         NoteDao dao = new NoteDao(getContext());  
  35.         List<NoteBean> beans =dao.findAll();  
  36.         for(NoteBean bean:beans){  
  37.               
  38.               
  39.             System.out.println(bean.toString());  
  40.               
  41.     }}  
  42.       
  43. }  



注意这是测试类 所以有
NoteDao dao = new NoteDao(getContext());
如果放到其他类中就要定义context上下文了。。这个问题和上文的
NoteSQLiteOpenHelper helper=new NoteSQLiteOpenHelper(this.getContext());
是一个问题。。不在赘述了。。内容没什么 注释比较多。才写了这么多。。不要因为写得多就觉得很麻烦。。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值