zoukankan      html  css  js  c++  java
  • Android笔记之数据库操作

    1、创建数据库

    你只要继承 SQLiteOpenHelper 类,就可以轻松的创建数据库。SQLiteOpenHelper 类根据开发应用程序的需要,封装了创建和更新数据库使用的逻辑。SQLiteOpenHelper 的子类,至少需要实现三个方法:

    • 构造函数,调用父类 SQLiteOpenHelper 的构造函数。这个方法需要四个参数:上下文环境(例如,一个 Activity),数据库名字,一个可选的游标工厂(通常是 Null),一个代表你正在使用的数据库模型版本的整数。
    • onCreate()方法,它需要一个 SQLiteDatabase 对象作为参数,根据需要对这个对象填充表和初始化数据。
    • onUpgrage() 方法,它需要三个参数,一个 SQLiteDatabase 对象,一个旧的版本号和一个新的版本号,这样你就可以清楚如何把一个数据库从旧的模型转变到新的模型。

    下面示例代码展示了如何继承 SQLiteOpenHelper 创建数据库:

    public class CourseOpenHelper extends SQLiteOpenHelper {
    
        private static String name="MyCourse.db";// 数据库名称
        private static int version=2;// 数据库版本号
    
        public CourseOpenHelper(Context context) {
            // name 若为空,则创建在内存中
            super(context, name, null, version);
            // TODO Auto-generated constructor stub
        }
        /*
         * The database is not actually created or opened until one of
         * getWritableDatabase() or getReadableDatabase() is called.
         */
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            // TODO 创建数据库后,对数据库的操作
            //在数据库中创建表Course
            String sql = "create table Course(_id integer primary key autoincrement,coursename text,room text)";
            db.execSQL(sql);
        }
    
         //更改数据库版本的操作
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // TODO 更改数据库版本的操作
        }

    }

     2 数据库操作

    package dao;
    
    import java.sql.Timestamp;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import service.StudentInfoService;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteConstraintException;
    import android.database.sqlite.SQLiteDatabase;
    import android.util.Log;
    
    import com.utils.CommonUrl;
    import com.utils.DbOpenHelper;
    import com.utils.GsonUlits;
    import com.utils.HttpClientUtils;
    
    public class StudentInfoDao implements StudentInfoService {
    
        private DbOpenHelper helper = null;
    
        public StudentInfoDao(Context context) {
            super();
            helper = new DbOpenHelper(context);
        }
    
        @Override
        public boolean fillStudentInfo(Object[] infolist) {
            // TODO Auto-generated method stub
            boolean flag = false;
            // 实现对数据库的添加,删除和修改功能
            SQLiteDatabase database = null;
            try {
                String sql = "insert into StuInfo(stuid ,name ,sex ,birthday ,xueyuan ,zhuanye, banhao,tel ,qq) values (?,?,?,?,?,?,?,?,?)";
                database = helper.getWritableDatabase();
                database.execSQL(sql, infolist);
                flag = true;
            } catch (SQLiteConstraintException e) {
                // column stuid is not unique (code 19)
                e.printStackTrace();
            }
            if (!flag) {
                String sql = "update StuInfo set name=? ,sex=? ,birthday=? ,xueyuan=? ,zhuanye=?, banhao=? ,tel=?,qq=? where stuid=?";
                database = helper.getWritableDatabase();
                String stuid = (String) infolist[0];
                for (int i = 0; i < 8; i++) {
                    infolist[i] = infolist[i + 1];
                }
                infolist[8] = stuid;
                database.execSQL(sql, infolist);
                flag = true;
            }
            return flag;
        }
    
        @Override
        public Map<String, String> getSimpleInfo(String selection,
                String[] selectionArgs) {
            // TODO Auto-generated method stub
    
            Map<String, String> map = new HashMap<String, String>();
            SQLiteDatabase database = null;
            Cursor cursor = null;// query返回的对象是Cursor
            try {
                database = helper.getWritableDatabase();
                // String[] co = { "coursename", "room", "teacher", "week" };
                // 在2.X版本下query方法汇出错误:
                // java.lang.NoSuchMethodError:
                // android.database.sqlite.SQLiteDatabase.query
                cursor = database.query(true, "StuInfo", null, selection,
                        selectionArgs, null, null, null, null, null);
                int cols_num = cursor.getColumnCount();
                while (cursor.moveToNext()) {
                    for (int i = 0; i < cols_num; i++) {
                        String cols_name = cursor.getColumnName(i);
                        String cols_value = cursor.getString(cursor
                                .getColumnIndex(cols_name));
                        if (cols_value == null) {
                            cols_value = "";
                        }
                        Log.i(i + "", "cols_name=" + cols_name + ",cols_value="
                                + cols_value);
                        map.put(cols_name, cols_value);
                    }
                }
    
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            } finally {
                if (database != null) {
                    database.close();
                }
            }
            return map;
        }
    
        @Override
        public boolean poststudent(Map<String, String> map) {
            // TODO Auto-generated method stub
            Map<String, String> info = new HashMap<String, String>();
            info.put("student.stuid", map.get("stuid"));
            info.put("student.name", map.get("name"));
            info.put("student.sex", map.get("sex"));
            info.put("student.xueyuan", map.get("xueyuan"));
            info.put("student.zhuanye", map.get("zhuanye"));
            info.put("student.banhao", map.get("banhao"));
            info.put("student.birthday", map.get("birthday"));
            String result = HttpClientUtils.sendHttpclientPost(
                    CommonUrl.Add_Student, info, "utf8");
            if (result.contains("成功"))
                return true;
            return false;
        }
    
        @Override
        public List<Map<String, Object>> getstudentlist(String banhao) {
            Map<String, String> map = new HashMap<String, String>();
            map.put("tmp", "");
            // TODO Auto-generated method stub
            String jsonString = HttpClientUtils.sendHttpclientPost(
                    CommonUrl.Student_List, map, CommonUrl.encode);
            if (jsonString.equals(""))
                return null;
            List<Map<String, Object>> list = GsonUlits
                    .getListKeyapFromGson(jsonString);
            return list;
        }
    
        @Override
        public List<Map<String, String>> getMoreInfo(String selection,
                String[] selectionArgs) {
            // TODO Auto-generated method stub
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            SQLiteDatabase database = null;
            Cursor cursor = null;// query返回的对象是Cursor
            try {
                database = helper.getWritableDatabase();
    
                cursor = database.query(true, "StuInfo", null, selection,
                        selectionArgs, null, null, null, null, null);
                int cols_num = cursor.getColumnCount();
                while (cursor.moveToNext()) {
                    Map<String, String> map = new HashMap<String, String>();
                    for (int i = 0; i < cols_num; i++) {
                        String cols_name = cursor.getColumnName(i);
                        String cols_value = cursor.getString(cursor
                                .getColumnIndex(cols_name));
                        if (cols_value == null) {
                            cols_value = "";
                        }
                        Log.i(i + "", "cols_name=" + cols_name + ",cols_value="
                                + cols_value);
    
                        map.put(cols_name, cols_value);
                    }
                    list.add(map);
                }
    
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            } finally {
                if (database != null) {
                    database.close();
                }
            }
            return list;
        }
    
        @Override
        public boolean addMessage(String body, String stuid, String type) {
            // TODO Auto-generated method stub
    
            boolean flag = false;
            // 实现对数据库的添加,删除和修改功能
            SQLiteDatabase database = null;
            Timestamp ts = new Timestamp(System.currentTimeMillis());
            Object[] infolist = { stuid, body, ts, type };
            try {
                String sql = "insert into Message(stuid ,body ,timestamp,type) values (?,?,?,?)";
                database = helper.getWritableDatabase();
    
                database.execSQL(sql, infolist);
                flag = true;
            } catch (SQLiteConstraintException e) {
                // column stuid is not unique (code 19)
                e.printStackTrace();
            }
            return flag;
        }
    
        @Override
        public List<Map<String, String>> getMessageList(String stuid) {
            // TODO Auto-generated method stub
            List<Map<String, String>> list = new ArrayList<Map<String, String>>();
            SQLiteDatabase database = null;
            Cursor cursor = null;// query返回的对象是Cursor
            try {
                database = helper.getWritableDatabase();
    
                String selection = "stuid=?";
                String[] selectionArgs = { stuid };
                cursor = database.query(true, "Message", null, selection,
                        selectionArgs, null, null, "timestamp", null, null);
                int cols_num = cursor.getColumnCount();
                while (cursor.moveToNext()) {
                    Map<String, String> map = new HashMap<String, String>();
                    for (int i = 0; i < cols_num; i++) {
                        String cols_name = cursor.getColumnName(i);
                        String cols_value = cursor.getString(cursor
                                .getColumnIndex(cols_name));
                        if (cols_value == null) {
                            cols_value = "";
                        }
    
                        map.put(cols_name, cols_value);
                    }
                    list.add(map);
                }
    
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            } finally {
                if (database != null) {
                    database.close();
                }
            }
            return list;
        }
    }

    Done!

  • 相关阅读:
    框架集。样式表
    2017.11.23知识点整理
    HTML5的标签
    HTML5大体概括截图
    2017.11.21 通用标签及属性
    2017.11.21 课程随记
    JavaScript数组
    JavaScript语句
    javascript基础知识
    不用alert提示的非空表单验证
  • 原文地址:https://www.cnblogs.com/xingyyy/p/3314776.html
Copyright © 2011-2022 走看看