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

来源:互联网 发布:蜘蛛侠淘宝客官网 编辑:程序博客网 时间:2024/04/28 23:05

android下创建数据库的步骤:

1.创建一个数据库打开的帮助类  继承SQLiteOpenHelper
2. 构造方法 设置数据库文件的名称  设置游标工厂 null  数据库的版本 1
3. 填写 onCreate()方法  数据库表结构的初始化  数据库第一次被创建的时候 调用的方法

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

package com.example.note.db;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.database.sqlite.SQLiteOpenHelper;public class NoteSQLiteOpenHelper extends SQLiteOpenHelper {/** * @param context 上下文 ; * @param name 数据库的名称 *  * @param cursorfactory 游标工厂null为默认的,是从第一条开始查询  *  * @param version 数据库的版本号从1开始。 */public NoteSQLiteOpenHelper(Context context) {super(context, "note123.db", null, 1);// TODO Auto-generated constructor stub}/** *oncreate 方法会在数据库第一次创建的时候被调用 适合做数据库表结构的初始化  * */public void onCreate(SQLiteDatabase db) {// TODO Auto-generated method stub//db.execSQL("create table account (id integer primary key autoincrement , name  varchar(20), money varchar(20) )");db.execSQL("create table account (id integer primary key autoincrement , " +"name  varchar(20), money varchar(20) )");//执行sql语句,可以建立表 varchar() 代表String类型}@Overridepublic void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {System.out.println("更新了");//当数据库有变化的时候会打印这条内容。没变化是不会打印这条内容的。}}

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

其中要继承SQLiteOpenHelper的方法为

public NoteSQLiteOpenHelper(Context context, String name,CursorFactory factory, int version) {super(context, name, factory, version);// TODO Auto-generated constructor stub}
只是演示,也为了调用方便只保留了Context的参数。其他参数都在super()中可以自动改变。如果有许多数据库。可以不删除元素 动态的添加 数据库的名字版本等。。

NoteSQLiteOpenHelper helper=new NoteSQLiteOpenHelper(this.getContext());//实例化要测试的数据     要测试所以要有上下文//注意:只有执行了getWritableDatabase 或者getreadabledatabase() 数据库才会被创建helper.getWritableDatabase();

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

//因为任何一个操作都需要得到NoteSQLiteOpenHelper helper//把他放在构造方法里面初始化private NoteSQLiteOpenHelper helper;public NoteDao(Context context) { //在构造方法里面就进行初始化 helper=new NoteSQLiteOpenHelper (context);}
helper.getWritableDatabase();//每个增删改查只写这一句就可以了,减少代码复用 


接下来建立一个测试类。。
1。继承AndroidTestCase 
2。.更改 AndroidManifest.xml 的内容
package com.example.note.test;import com.example.note.db.NoteSQLiteOpenHelper;import android.test.AndroidTestCase;public class TestNoteOpenHelper extends AndroidTestCase {public void testCreateDB() throws Exception{//要测试所以要有上下文  getContext 是获取到测试框架的一个虚拟的模拟的假的上下文NoteSQLiteOpenHelper helper=new NoteSQLiteOpenHelper(this.getContext());//实例化要测试的数据     要测试所以要有上下文//注意:只有执行了getWritableDatabase 或者getreadabledatabase() 数据库才会被创建helper.getWritableDatabase();//helper.getReadableDatabase();}}

AndroidManifest.xml 加入的内容为
<instrumentation        android:name="android.test.InstrumentationTestRunner"        android:targetPackage="com.example.note" /> <uses-library android:name="android.test.runner" />

这两句其中 com.example.note 为要测试的包名
具体内容是
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.example.note"    android:versionCode="1"    android:versionName="1.0" >    <uses-sdk        android:minSdkVersion="8"        android:targetSdkVersion="17" />  <instrumentation        android:name="android.test.InstrumentationTestRunner"        android:targetPackage="com.example.note" />        <application        android:allowBackup="true"        android:icon="@drawable/ic_launcher"        android:label="@string/app_name"        android:theme="@style/AppTheme" >        <uses-library android:name="android.test.runner" />        <activity            android:name="com.example.note.MainActivity"            android:label="@string/app_name" >                        <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>    </application></manifest>

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


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


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

package com.example.note.domain;public class NoteBean {private int id;private float money;private String name;public int getId() {return id;}public void setId(int id) {this.id = id;}public float getMoney() {return money;}public void setMoney(float money) {this.money = money;}public String getName() {return name;}public void setName(String name) {this.name = name;}public NoteBean(int id, float money, String name) {  //用于批量给三个变量复制。。super();this.id = id;this.money = money;this.name = name;}public NoteBean(){}@Overridepublic String toString() {return "NoteBean [id=" + id + ", money=" + money + ", name=" + name+ "]";}}

增删改查。。属于最简单的
package com.example.note.db.dao;import java.util.ArrayList;import java.util.List;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import com.example.note.db.NoteSQLiteOpenHelper;import com.example.note.domain.NoteBean;/** *记账本的dao *@author Administrator  */ public class NoteDao {//因为任何一个操作都需要得到NoteSQLiteOpenHelper helper//把他放在构造方法里面初始化private NoteSQLiteOpenHelper helper;public NoteDao(Context context) { //在构造方法里面就进行初始化 helper=new NoteSQLiteOpenHelper (context);}/** *添加一条账目信息到数据库 *@param name 花销名称 *@param 金额 */public void add (String name,float money){//NoteSQLiteOpenHelper helper=new NoteSQLiteOpenHelper();SQLiteDatabase db=helper.getWritableDatabase();db.execSQL("insert into account(name,money) values(?,?)",new Object[]{name,money});//记住;关闭数据库---否则打开过多数据库会导致数据库无法使用db.close();}public void delete(int id){SQLiteDatabase db=helper.getWritableDatabase();db.execSQL("delete from account where id=?", new Object[]{id});db.close();}public void update(int id,float newMoney){SQLiteDatabase db=helper.getWritableDatabase();db.execSQL("update account set money=? where id=?", new Object[]{newMoney,id});}/** *返回数据库中所有的内容  */  public List<NoteBean> findAll(){SQLiteDatabase db=helper.getWritableDatabase();List<NoteBean> noteBeans=new ArrayList<NoteBean>();//获取到数据库查询的结果游标Cursor cursor =db.rawQuery("select * from account", null);//cursor.moveToPosition(arg0);// 直接定位到查询的哪一位while(cursor.moveToNext()){//向下查询//int id=cursor.getInt(0);//得到第几列的内容//String name= cursor.getString(2);//float money=cursor.getFloat(1);   //这样貌似容易搞混。如果一百个那绝对蒙了int id=cursor.getInt(cursor.getColumnIndex("id"));String name= cursor.getString(cursor.getColumnIndex("name"));float money=cursor.getFloat(cursor.getColumnIndex("money")); NoteBean bean=new NoteBean(id,money,name); //把三个数传到NoteBean中。这样就可以调用了noteBeans.add(bean);//把bean中的数据存到list集合中bean=null;//节省内存}db.close();return noteBeans;}}

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


继续。建立一个测试类。测试增删改查是否有用。。
package com.example.note.test;import java.util.List;import com.example.note.db.dao.NoteDao;import com.example.note.domain.NoteBean;import android.test.AndroidTestCase;import android.widget.Toast;public class TestNoteDao extends AndroidTestCase {//增加public void testAdd() throws Exception {NoteDao dao = new NoteDao(getContext());for (int i = 0; i < 20; i++) {dao.add("3月" + i + "号打酱油", 3.10f + i);}}//更新public void testupdate() throws Exception {NoteDao dao = new NoteDao(getContext());dao.update(2, 9.88f);}//删除public void testDelete() throws Exception {NoteDao dao = new NoteDao(getContext());dao.delete(4);}//查找public void testFindAll() throws Exception {NoteDao dao = new NoteDao(getContext());List<NoteBean> beans =dao.findAll();for(NoteBean bean:beans){System.out.println(bean.toString());}}}



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

0 0
原创粉丝点击