菜单

Android–SQLite(增,删,改,查)操作实例代码

2018年12月15日 - sqlite

需要5个类:

复制代码 代码如下:

1.实体类:Person.java

<%@ page language=”java” import=”java.util.*”
pageEncoding=”UTF-8″%>

2.空洞类:SQLOperate.java(封装了针对数据库的操作)

<html>
    <head>
        <title>extJs中时常由此到的增删改查操作的以身作则代码</title>
        <!– CommonJs.jsp 为 ExtJS 引入的路 –>
        <%@ include file=”../extJs/CommonJs.jsp”%>
        <script type=”text/javascript”><!–
        /**
        * 作     者: 花 慧
        * 时     间: 2009年12月22日
        * 内 容: extJs中常因而到之加码,删,改,查操作
        */    

3.助手类:DBOpenHelper.java(继承SQLiteOpenHelper)

        //设置每页呈现的行数默认为10

4.实现类:SQLOperateImpl.java(实现抽象类SQLOperate.java)

        var QUERY_PAGE_SIZE = 10;

5.测试类:Test.java(继承AndroidTestCase)

        /**
        * SearchQueryForm():绘制查询表单
        */
        function searchQueryForm()
        {
         //form
使用的当儿提议要为部分变量,可以通过Ext.getCmp(“”)去获取form

1.Person.java

         var queryForm = null;
            queryForm = new Ext.FormPanel({
                id:’queryForm’, //指定queryForm的Id
                renderTo:’searchPanel’, //指向form所在的div层
                labelWidth:70, //label标签的width占页面的比例
                region:’north’,
                border:false,
//以展现面板的body元素的分界,虚假隐藏起来(默认为true)
                badyBorder:false,
//呈现面板的body元素,假缘逃匿它(默认为true的中界限)
                labelAlign:’right’, //label标签的指向齐情势
                frame:true,
//自定义面板的周边界,边界宽度1px。默认为false
                title:’用户新闻查询’, //form的题
                /**
                *buttons:在FormPanel中按钮的汇聚
                */
                buttons:[{handler:addForm,text:’新增’},
                        {handler:submitForm,text:’查询’},
                        {handler:resetForm,text:’重置’}],
             /**
             * items: 在FormPanel中不得缺失的有的
             */
             items:[{
         /**
              * layout:extJs容器组件,可以装它的亮风格
              *
它的有效值有absolute,accordion,anchor,border,card,fit,form and table
共9种植
              */
                 layout:’column’,
                 items:[
                     {
                         columnWidth:.5,
                         layout:’form’,
                         items:{
                             name:’userId’,
                             hiddenName:’userId’,
                             xtype:’textfield’,
                             fieldLabel:’用户编码’,
                             maxLength:’50’,
                             vtype:’specialChar’,
                             anchor:’80%’
                         }
                     },{
                         columnWidth:.5,
                         layout:’form’,
                         items:{
                             name:’userName’,
                             hiddenName:’userName’,
                             xtype:’textfield’,
                             fieldLabel:’用户名称’,
                             maxLength:’100′,
                             vtype:’specialChar’,
                             anchor:’80%’
                         }
                     }
                 ]
             }]
            });
        }
        /**
        * showUserForm():绘制添加表单
        */
        function showUserForm()
        {
         //将变量定义成有变量,避免每一回都大成一个初目的

复制代码 代码如下:

            var userForm = null;
            userForm = new Ext.FormPanel({
                id:’conditionForm’,
                labelWidth:’80’,
                labelAlign:’right’,
                border:false,
                bodyBorder:false,
             frame:true,
             items:[
                 layout:’column’,
                 items:[
                 {
                     columnWidth:’.8′,
                     items:{
                         name:’userInfo.userId’,
                         hiddenName:’userInfo.userId’,
//hiddenName动态的绑定数据库被对应的字段
                         xtype:’textField’,
//xtype可以分为三类,textField(Field)为表单域的控件
                         fieldLabel:’用户编码<font
color=red>*</font>’,//控件前的文书表明
                         labelSeparator:”,
                         blankText : ‘填写用户编码’,
//为空的文本框提醒信息
                         allowBlank:false,      //不允为空
                         maxLength:’50’,     
//文本框允许输入的无比可怜之长短,最小的minLength
                         vtype:’specialChar’,
                         anchor:’80%’
                     }
                 },{
                     columnWidth:’.8′,
                     items:{
                         name:’userInfo.userName’,
                         hiddenName:’userInfo.userName’,
                         xtype:’textField’,
                         fieldLabel:’用户姓名<font
color=red>*</font>’,
                         labelSeparator:”,
                         blankText:’填写用户姓名’,
                         allowBlank:false,
                         maxLength:’100′,
                         vtype:’specialChar’,
                         anchor:’100%’
                     }
                 },{
                     columnWidth:’.8′,
                     items:{
                         name:’userInfo.pwd’,
                         hiddenName:’userInfo.pwd’,
                         xtype:’textField’,
                         inputType:’password’,
                         fieldLabel:’用户密码<font
color=red>*</font>’,
                         labelSeparator:”,
                         blankText:’填写用户密码’,
                         allowBlank:false,
                         maxLength:’12’,
                         minLength:’6′,
                         value:’123456′, //用户默认的心腹
                         anchor:’100%’
                     }
                 },{
                     columnWidth:’.8′,
                     items:{
                         name:’rPwd’,
                         hiddenName:’rPwd’,
                         xtype:’textField’,
                         inputType:’password’,
                         fieldLabel:’确认密码<font
color=red>*</font>’,
                         labelSeparator:”,
                         blankText:’二次输入的秘密要相同’,
                         allowBlank:false,
                         vtype:’pwdRange’,
                         pwdRange:{begin:’userInfo.pwd’,end:’rPwd’},
                         maxLength:’12’,
                         anchor:’100%’
                     }
                 }]
             ]
            });
        }
        /**
        * editUserForm():绘制修改表单
        */
        function editUserForm(){
            //将变量定义成有变量,防止每趟都分外成一个新对象

package com.mrzhu.sqltite;

            var userForm = null;
            userForm = new Ext.FormPanel({
                id:’editForm’,
                labelWidth:’80’,
                labelAlign:’right’,
                border:false,
                bodyBorder:false,
             frame:true,
             items:[
                 layout:’column’,
                 items:[
                 {
                     columnWidth:’.8′,
                     items:{
                         name:’userInfo.userId’,
                         hiddenName:’userInfo.userId’,
//hiddenName动态的绑定数据库中对应之字段
                         xtype:’textField’,
//xtype可以分成三类,textField(Field)为表单域的控件
                         fieldLabel:’用户编码’, //控件前的文书表达
                         labelSeparator:’:’,
                         readOnly:true, //文本框只念
                 disabled:true, //文本框褐色,区别与外的文本框颜色
                         blankText : ‘填写用户编码’,
//为空的文本框提醒音讯
                         allowBlank:false,      //不允许吗空
                         maxLength:’50’,     
//文本框允许输入的最特其它长度,最小之minLength
                         //字母开首,且只好存在字母和数字长度为2届12各种

public class Person {

                         regex :
/^[a-zA-Z]{1}([a-zA-Z0-9]|[_]){1,11}$/,
                 regexText : ‘用户编码必须为字母起首,长度2-12员!’,
                         anchor:’90%’
                     }
                 },{
                     columnWidth:’.8′,
                     items:{
                         name:’userInfo.userName’,
                         hiddenName:’userInfo.userName’,
                         xtype:’textField’,
                         fieldLabel:’用户姓名’,
                         labelSeparator:’:’,
                         blankText:’填写用户姓名’,
                         allowBlank:false,
                         maxLength:’100′,
            
            //只含汉字、数字、字母、下划线不可知以下划线先导和结尾

 private int _id;
 private String name;

                         regex :
/^(?!_)(?!.*?_$)[a-zA-Z0-9_\u4e00-\u9fa5]+$/,
                 regexText :
‘只含有汉字、数字、字母、下划线无法以下划线开头和终极!’,
                         anchor:’90%’
                     }
                 },{
                  columnWidth:’.2′,
         items:{
     hiddenName:”infoFill”,
         name:”infoFill”,
         xtype:’label’,
         html:'<font color=red>*</font>’,
         labelSeparator:”,
         anchor:’100%’
         }
                 },{
                     columnWidth:’.8′,
                     items:{
                         name:’userInfo.pwd’,
                         hiddenName:’userInfo.pwd’,
                         xtype:’textField’,
                         inputType:’password’,
                         fieldLabel:’用户密码<font
color=red>*</font>’,
                         labelSeparator:’:’,
                         blankText:’填写用户密码’,
                         allowBlank:false,
                         maxLength:’12’,
                         minLength:’6′,
                         anchor:’90%’
                     }
                 },{
                  columnWidth:’.2′,
         items:{
     hiddenName:”infoFill”,
         name:”infoFill”,
         xtype:’label’,
         html:'<font color=red>*</font>’,
         labelSeparator:”,
         anchor:’100%’
         }
                 },{
                     columnWidth:’.8′,
                     items:{
                         name:’rPwd’,
                         hiddenName:’rPwd’,
                         xtype:’textField’,
                         inputType:’password’,
                         fieldLabel:’确认密码<font
color=red>*</font>’,
                         labelSeparator:’:’,
                         blankText:’二不行输入的机密而相同’,
                         allowBlank:false,
            
            //在extCommon.js文件被定义二蹩脚输入的密码相同验证pwdRange

 public int getId() {
  return _id;
 }

                         //
vtype为求证的法,淌假如通用的印证,请在术被定义,假使是特例,可以以regex
                         vtype:’pwdRange’,
                         pwdRange:{begin:’userInfo.pwd’,end:’rPwd’},
                         maxLength:’12’,
                         anchor:’90%’
                     }
                 },{
                  columnWidth:’.2′,
         items:{
     hiddenName:”infoFill”,
         name:”infoFill”,
         xtype:’label’,
         html:'<font color=red>*</font>’,
         labelSeparator:”,
         anchor:’100%’
         }
                 }]
             ]
            });
        }
        /**
        * onReady:该文件准备好(在onload和图像加载从前)
        */
        Ext.onReady(function(){

 public void setId(int _id) {
  this._id = _id;
 }

            searchQueryForm();
            //获取查询form

 public String getName() {
  return name;
 }

            var queryForm = Ext.getCmp(“queryForm”).getForm();
         /**
         * layout设置也border表示页面将分开也东南西北中五单部分
         * 这里代表centerPanel放在中间
         */
            var layout = new Ext.Viewport({
                layout:’border’,
                defaluts:{border:false,bodyBorder:false,activeTab:0},
         
items:[queryForm,{id:’centerPanel’,region:’center’,height:document.body.clientHeight,contentEl:’mainDiv’}]
            });
            //页面加载的上,默认数据查询页面显示用户信息列表

 public void setName(String name) {
  this.name = name;
 }

            submitForm();
        });

 @Override
 public String toString() {
  return “Person [id=” + _id + “, name=” + name + “]”;
 }

        //查询消息
        var store = new Ext.data.Store({
            url:’../user/doGetPageList.action’, //action的路径
            reader:new Ext.data.JsonReader({
                root:’userList’,
//从struts2.0里边传递过来的参数:用户之汇聚
                totalProperty:’rowTotal’,
//从struts2.0内传递过来的参数:总共的音之行数
                id:’userId’,
                successPropery:’success’},
                [‘userId’,’userName’,’pwd’]
            )
        });

 public Person() {
  super();
 }

        /**
        * callback:调用的函数
        */
        function getMsg()
        {

 public Person(int _id, String name) {
  super();
  this._id = _id;
  this.name = name;
 }
}

        }
        /**
        * 模糊查询
        */
        function submitForm()
        {
         //初始化grid
            var grid = null;
            //复选框
            var sm = new Ext.grid.CheckboxSelectionModel({
                dataIndex:’id’,
                width:’20’
            });
            /**
         *  sortabel:(可选)即便真若排序允许在此列
         * 
renderer:(可选)用于转移于定数据值单元格的HTML标记的效能。假如没有点名,默认渲染器使用的原本数据值。
         * 在renderer:function
createButton(参数)这里的参数可以无要多独
         *  鼠标移动图片及成为”手”是:style=”cursor:hand”
         */
            var colM = new Ext.grid.ColumnModel(
                [sm,{header:’用户账号’,dataIndex:’userId’,align:’center’,sortable:true},
                {header:’用户姓名’,dataIndex:’userName’,align:’center’,sortabel:true},
                {header:’删除’,dataIndex:’id’,align:’center’,renderer:function
createButton(){
                    return ‘<img alt=”删除” style=”cursor:hand”
style=”cursor:hand” src=”../images/hh_framework/ico_delete.gif”
src=”images/hh_framework/ico_delete.gif” />’;}},
                {header:’编辑’,dataIndex:’userId’,align:’center’,renderer:function
createButton(userId, metadata, record){
                    return ‘<a style=”cursor:hand”
style=”cursor:hand” onclick=updateForm(‘+userId+’)
>’+record.get(‘userName’)+’的新闻修改’+'</a>’;}}]
            );

2.SQLOperate.java

         //获取查询表单

复制代码 代码如下:

            var form = Ext.getCmp(“queryForm”).getForm();

package com.mrzhu.sqltite;

            //判断是否通过认证,如果没有请求直接关闭
            if(!form.isValid())
            {
                Ext.Msg.alert(“系统提醒”,”查询数据未得法,请确认输入!”);
                return ;
            }
            //差选queryform中查询的数目参数

import java.util.List;

            store.baseParams = form.getValues();
            /**
            *
getLimitCount():获取分页每页行数,假使不传值,则会取默认值
            *
Start表示读取数据的最先地方、limit表示每一次读取多少条数
            * callback:getMsg 代表回调时,执行函数 getMsg。可粗略
            */

/**
 * 增删改查
 * @author ZLQ
 *
 */
public interface SQLOperate {
 public void add(Person p);
 public void delete(int id);
 public void updata(Person p);
 public List<Person> find();
 public Person findById(int id);
}

            store.load({params:{start:0,limit:getLimitCount()},
callback:getMsg});
            if(grid == null)
            {
                grid = new Ext.grid.EditorGridPanel({
                    renderTo:”mainDiv”, //grid查询结果对突显的div层
                    title:”用户查询结果”, //grid标题
                    width:document.body.clientWidth,
//设置grid的width的值
                    hight:document.doby.clientHight-100,//设置hight的值
                    viewConfig:{forceFit:true}, //设置列数的满载窗口
                    loadMask:true,                //在加载数据平常之遮罩效果
                    stripeRows:true, //隔行换色
                    region:’center’,
//那个是设置于ViewPort中突显的地点
                    cm:colM, //定义的排列
                    ds:store, //定义的数据源
                    border:false,
                    bodyBorder:false,
                    sm:sm, //定义的复选框

3.DBOpenHelper.java

                    //listeners:包含一个或者三个事件处理程序让补加到这多少个目的开首化过程中

复制代码 代码如下:

                    listeners:{cellclick:renderPage},
                    /**
                 * bbar: new Ext.PagingToolbar部分凡概念分页工具栏,
                 *
这里的分页控件栏还由此到了1个温馨定义之插件,就是可择每页展现小条之
                    * plugins : [new
Ext.ux.PageSizePlugin()],参考Ext的API
                 * 要兑现分页,后台必须来total属性,表示并多少条数
                 */

package com.mrzhu.sqltite;

                    bbar:new Ext.PagingToolbar({
                        items:[{
                            xtype:’button’,
                            text:’删除所选’,
                            handler:delUserAll, //自定义执行动
                            pressed:true
                        }],
                        id:’pageToolBar’,
                        pageSize:QUERY_PAGE_SIZE,
//每页的行数默认为:QUERY_PAGE_SIZE
                        store:store,
                        displayInfo:true,
                        displayMsg:’显示第{0}条到{1}条记录,共{2}条记录’,
                        emptMsg:’没有记录’,
                        plugins:[new Ext.ux.PageSizePlugin()]
                    })
                });
            }
            grid.render();
        }
        /**
        * 扩充用户音讯
        */
        function addForm()
        {
            showUserForm();
            //获取绘制用户窗口的form

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

            var userForm = Ext.getCmp(“conditionForm”).getForm();
            //起头化用户增长的窗口的Id

/**
 * 助手类
 * @author ZLQ
 *
 */
public class DBOpneHelper extends SQLiteOpenHelper {

            var addUserWin = Ext.getCmp(“addWin”);
            if(addUserWin == null)
            {
                addUserWin = new Ext.Window({
                    width:500, //初叶窗口的width的值
                    x:100, //窗口的先导化x方向的职
                    y:100, //窗口的先河化y方向的职位
                    plain:true,
                    modal:true, //形式窗口,默认为false
                    closeAction:”hide”, //默认窗口隐藏
                    resizable:false, //窗口的尺寸不同意拖动,默认为true
                    id:”addWin”, //指定用户增长窗口的Id
                    items:[userForm],
                    buttons:[
                 {text:’保存’,handler:function(){
                     if(userForm.form.isValid()){
                      userForm.form.doAction(‘submit’,{
                             url:’../user/addUser.action’,
                
            params:{roleId:userForm.form.findField(‘userId’).getValue()},
                             method:’post’,
//数据提交的道:有个别种get,post
                             waitTitle:’指示音讯’,
//数据提交等的滚条
                             waitMsg:’保存数据,请稍候…’,
//滚动条升迁的内容
                          success:function(form,action){
                          var message = action.result.message;
                              if(message == null){
                             
Ext.Msg.alert(“指示音信”,”用户新闻上加事业有成!”);
                              store.reload();
                              addUserWin.hide();
                              }else{
                              Ext.Msg.alert(“指示信息”,message);
                              }
                          },
             failure:function(form,action){
             Ext.Msg.alert(‘提醒消息’,”新用户增长失败!”);
             return;
             }
             });
                 }else {
            
        Ext.Msg.alert(“指示消息”,”表单有误,请对填写!”);
                 }
                 }},
            
    {handler:function(){userForm.form.reset();},text:’重置’},
            
    {handler:function(){addUserWin.hide();},text:’关闭’}]
                });
            }
            addUserWin.show();
        }
        /**
        * 删除用户信息
        */
        function delForm(userId)
        {
            Ext.Msg.confirm(‘指示信息’,’你规定要推行删除操作也?’,function(btn){
                if(btn == ‘yes’)
                {
                     /**
                 * 数据提交的平等种植方法:Ext.Ajax.request({});
                 */
                    Ext.Ajax.request({
                        url:’../user/delUser.action’,
                        params:{userId:userId},
                        method:’post’,
                        success:function(o)
                        {
                            var info = Ext.decode(o.responseText);
                            Ext.Msg.alert(“提醒音信”,info.message);
                            store.reload();
                            return ;
                        },
                        failure:function(form,action)
                        {
                            Ext.Msg.alert(“提醒消息”,”用户信息去失利!”);
                            return ;
                        }
                    });
                }
            });
        }
        /**
        * 批量删除事件
        */
        function delUserAll()
        {
         //grid中复选框被选中的宗

 private static final int VERSION = 1;//版本
 private static final String DB_NAME = “people.db”;//数据库名
 public static final String STUDENT_TABLE = “student”;//表名
 public static final String _ID = “_id”;//表中的列名
 public static final String NAME = “name”;//表中的列名
 //创造数据库语句,STUDENT_TABLE,_ID ,NAME的前后都要加空格
 private static final String CREATE_TABLE = “create table ” +
STUDENT_TABLE + ” ( ” + _ID + ” Integer primary key autoincrement,” +
NAME + ” text)”;

             var rows = grid.getSelectionModel().getSelections();
             //user_id:所有入选的用户Id的集合使用’,’隔开,起始化为空

 public DBOpneHelper(Context context) {
  super(context, DB_NAME, null, VERSION);
 }

             var user_id = ”;
         for(var i = 0;i<rows.length;i++)
         {
             if(i>0)
             {
                 user_id = user_id+’,’+rows[i].get(‘userId’);
             }else{
                 user_id = user_id+rows[i].get(‘userId’);
             }
         }
         //没有采纳而执行操作的对象

 //数据库第一蹩脚受创制时调用
 @Override
 public void onCreate(SQLiteDatabase db) {
  db.execSQL(CREATE_TABLE);
 }

             if(user_id == “”)
             {
                 Ext.Msg.alert(“提醒音讯”,”请捎而抹的对象”);
                 return ;
             }else{
            
    Ext.Msg.confirm(“指示音信”,”请确定要实践删除操作也?”,function
(btn){
                     if(btn == ‘yes’)
                     {
                         Ext.Ajax.request({
                             url:”../user/delAllUser.action”,
                             params:{id:user_id},
                             method:’post’,
                             success:function(o){
                                 var info =
Ext.decode(o.responseText);
            
                    Ext.Msg.alert(“指示信息”,info.message);
                                 store.reload();
                                 return ;
                             },
                             failure:function(form,action){
            
                    Ext.Msg.alert(“提醒新闻”,”用户音讯去战败!”);
                             }
                         });    
                     }
                 });
             }
        }
        /**
        * 修改用户消息
        * 参数userId:修改对象的Id
        */
        function updateForm(userId)
        {
            editUserForm();

 //版本升级时被调用
 @Override
 public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {

            var userForm = Ext.getCmp(“editForm”).getForm();
            Ext.Ajax.request({
                url:’../user/doGetOne.action’,
                params:{userId:userId},
                method:’post’,
                //从struts2.0里重回的参数

 }

                success:function(o)
                {
                 //读取action传递过来的对象参数
                 //docode:解码(解析)一个JSON字符串对象

}

                    var user = Ext.decode(o.responseText);

4.SQLOperateImpl.java

                    //用户编辑窗口的打开

复制代码 代码如下:

                    editUser(user);

package com.mrzhu.sqltite;

                    //将对象音讯显示在对应之form文本框中

import java.util.ArrayList;
import java.util.List;

                    userForm.form.findFiled(‘userInfo.userId’).setValue(user.userInfo.userId);
                    userForm.form.findFiled(‘userInfo.userName’).setValue(user.userInfo.userName);
                    userForm.form.findFiled(‘userInfo.pwd’).setValue(user.userInfo.pwd);
                    userForm.form.findFiled(‘rPwd’).setValue(user.userInfo.pwd);
                }
            });
        }
        /**
        * 用户音讯编辑窗口
        */
        function editUser(user){
            var userForm = Ext.getCmp(“editForm”).getForm();
            //得到用户编辑的窗口的目的
            var editUserWin = Ext.getCmp(“editWin”);
            //当为空的上以开展实例化

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

            if(editUserWin == null)
            {
                editUserWin = new Ext.Window({
             id:’editWin’,
                width:500,
                x:100,
                y:100,
                modal:true,
                resizable:false,
                closeAction:”hide”,
                title:’用户音信修改’,
                items:[userForm],
                buttons:[
                    {text:’保存’,handler:function(){
                        if(userForm.form.isValid())
                        {
                         /**
                         *
数据交到的亚栽艺术:form.doAction(‘submit’,{});
                         */
                            userForm.form.doAction(‘submit’,{
                                url:’../user/updUser.action’,
                                params:{userId:userForm.form.findField(‘userInfo.userId’).getValue()},
                                method:’post’,
                                waitTitle:’指示信息’,
                                waitMsg:’数据处理面临,请稍后….’,
                                //从struts2.0里无待回到的参数

public class SQLOperateImpl implements SQLOperate{

                                success:function(form,action)
                                {
                                    Ext.Msg.alert(“提醒音讯”,”用户音信修改成功!”);
                                    //查询的数码集合store刷新,实现页面自动刷新的法力

 private DBOpneHelper dbOpenHelper;

                                    store.reload();
                                    //将窗口关闭时,window.
hide()方法是藏,因此并无会师真销毁窗口对象

 public SQLOperateImpl(Context context) {
  dbOpenHelper = new DBOpneHelper(context);
 }

                                    editUserWin.hide();
                                    return ;
                                },
                                failure:function(form,action)
                                {
                                    Ext.Msg.alert(“指示信息”,”用户消息修改失利”);
                                    return ;
                                }
                            });
                        }else
                        {
                            Ext.Msg.alert(“提醒信息”,”表单有左,请复填写!”);
                        }
                    }},
                    {text:’关闭’,handler:function(){editUserWin.hide();}}]
             });
            }
            editUserWin.show();
        }
        /**
        * 重置页面查询表单
        */
        function resetForm()
        {
            Ext.getCmp(“queryForm”).getForm().reset();
        }

 /**
  * 增,用insert向数据库被插数据
  */
 public void add(Person p) {
  SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
  ContentValues values = new ContentValues();
  values.put(DBOpneHelper._ID, p.getId());
  values.put(DBOpneHelper.NAME, p.getName());
  db.insert(DBOpneHelper.STUDENT_TABLE, null, values);
 }

        /**
        * 每行单元格点击事件
        */
        function renderPage(grid,rowIndex,columnIndex,e)
        {
         //触发事件之对象的Id
            var id = grid.getStore().getAt(rowIndex).data[‘userId’];
            switch(columuIndex)
            {
                case 3:delForm(id);
                     break;
             /**
                *case 4:updateForm(id);
                *     break;
                */
             default:break;
            }
        }

 /**
  * 删,通过id删除数据
  */
 public void delete(int id) {
  SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
  db.delete(DBOpneHelper.STUDENT_TABLE, DBOpneHelper._ID + “=?”, new
String[]{String.valueOf(id)});
 }

// –></script>
    </head>

 /**
  * 改,修改指定id的数目
  */
 public void updata(Person p) {
  SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
  ContentValues values = new ContentValues();
  values.put(DBOpneHelper._ID, p.getId());
  values.put(DBOpneHelper.NAME, p.getName());
  db.update(DBOpneHelper.STUDENT_TABLE, values, DBOpneHelper._ID +
“=?”, new String[]{String.valueOf(p.getId())});
 }

    <body>
        <div id=”searchPanel”>
        </div>
        <div id=”centerPanel”>
        </div>
        <div id=”mainDiv”></div>
    </body>
</html>

 /**
  * 查,查询表中兼有的数额
  */
 public List<Person> find() {
  List<Person> persons = null;
  SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
  Cursor cursor = db.query(DBOpneHelper.STUDENT_TABLE, null, null,
null, null, null, null);
  if(cursor != null){
   persons = new ArrayList<Person>();
   while(cursor.moveToNext()){
    Person person = new Person();
    int _id =
cursor.getInt(cursor.getColumnIndex(DBOpneHelper._ID));
    String name =
cursor.getString(cursor.getColumnIndex(DBOpneHelper.NAME));
    person.setId(_id);
    person.setName(name);
    persons.add(person);
   }
  }
  return persons;
 }

卿可能感兴趣的篇章:

 /**
  * 查询指定id的多寡
  */
 public Person findById(int id) {
  SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
  Cursor cursor = db.query(DBOpneHelper.STUDENT_TABLE, null,
DBOpneHelper._ID + “=?”, new String[]{String.valueOf(id)}, null,
null, null);
  Person person = null;
  if(cursor != null && cursor.moveToFirst()){
   person = new Person();
   int _id = cursor.getInt(cursor.getColumnIndex(DBOpneHelper._ID));
   String name =
cursor.getString(cursor.getColumnIndex(DBOpneHelper.NAME));
   person.setId(_id);
   person.setName(name);
  }
  return person;
 }
}

5.Test.java

 

在AndroidManifest.xml中的<application></application>外添加

(targetPackage是现阶段工程的包名)

 

 <instrumentation

android:targetPackage=”com.mrzhu.sqltite”

android:name=”android.test.InstrumentationTestRunner”>

</instrumentation>

 

在<application></application>中添加<uses-library
android:name=”android.test.runner”/>

复制代码 代码如下:

package com.mrzhu.sqltite;

import java.util.List;

import android.test.AndroidTestCase;
import android.util.Log;

public class Test extends AndroidTestCase {
 public void testAdd() throws Exception{
  SQLOperateImpl test = new SQLOperateImpl(getContext());
  Person person = new Person(2, “Peter”);
  test.add(person);
 }

 public void testDelete() throws Exception{
  SQLOperateImpl test = new SQLOperateImpl(getContext());
  test.delete(1);
 }

 public void testUpdata() throws Exception{
  SQLOperateImpl test = new SQLOperateImpl(getContext());
  Person person = new Person(1, “Tom”);
  test.updata(person);
 }

 public void testFind() throws Exception{
  SQLOperateImpl test = new SQLOperateImpl(getContext());
  List<Person> persons = test.find();
  for (Person person : persons) {
   Log.i(“System.out”, person.toString());
  }
 }

 public void testFindById() throws Exception{
  SQLOperateImpl test = new SQLOperateImpl(getContext());
  Person person = test.findById(2);
  Log.i(“System.out”, person.toString());
 }
}

你或许感兴趣的稿子:

相关文章

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图