android中使用sqlite的数据库的基本操作

来源:互联网 发布:js获取表单某个数据 编辑:程序博客网 时间:2024/05/22 12:53

首先我们来了解一下SQLite的基本:

sqlite数据库的使用方式: 1.sqlite数据库数据类型: Intger/ varchar(10)/ float /double /char(10) /text2.SQL语句的回顾:2.1 创建表的语句:create table 表名(字段名称 数据类型 约束,字段名称 数据类型 约束......) create table person(_id Integer primary key,name varchar(10),age Integer not null)2.2 删除表的语句:drop table 表名drop table person2.3 插入数据的语音:insert into 表名[字段,字段] valuse(值1,值2.......)insert into person (_id,age) values(1,20)insert into person valuses(2,"ab",20)2.4 修改数据:update 表名 set 字段=新值 where 修改条件update person set name="ls",age =20 where _id=12.5 删除数据delete from 表名 where 删除的条件delete from person where _id=12.6 查询数据select 字段名 from 表名 where 查询条件 group by 分组的字段 having 筛选条件 order by 排序字段
select _id ,name from personselect * from person where _id<>1  //查询id不等于1的select * from person where _id=1 and age >18  //查询id为1,年龄大于18的数据select * form person where name like "%小%"  //查询名字中有小字的数据select * form person where name like "_小%"  //查询姓名的第二个字是小字的数据select * form person where name is null      //查询姓名为null的数据select * form person where age between 10 and 20 //查询年龄在10到20之间的数据select * form person where age>18 order by _id //查询年龄大于18的数据并且根据id排序


这里先让大家看看效果吧!

显示得到界面:

点击创建数据库后导出数据库可见:

点击插入将插入数据:

点击修改数据后:把zhengsan修改成了张三

点击删除后:


在平时我们使用的数据库比较少  所以呢Sql语句记不清的时候呢我们可以调用android API中的方法:

1.插入


2.修改:将王麻子的年龄修改成了100


接下来就是附上代码内容了:
而我们都知道SQLite是我们android默认使用的数据库所以说呢!我们使用起来比较方法:

1.首先我们新建一个MySqliteHelper类来继承我们的SqliteOpenHelper类并实现方法,以及该类的构造方法

/**Created by Administrator on 2016/12/6. * sqliteOperHelper * 1.提供了onCreate() onUpgrade()等创建数据库和更新数据可的方法 * 2.提供了获取数据库对象的函数 * @author diaobao-刘平 */public class MySqliteHelper extends SQLiteOpenHelper {    /**     * 构造函数     *     * @param context 上下文对象     * @param name    表示数据库名称     * @param factory 游标工厂     * @param version 版本号 >=1     */    public MySqliteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {        super(context, name, factory, version);    }    public MySqliteHelper(Context context) {        super(context, Constant.DATABASE_NAME, null, Constant.DAABASE_VERSION);    }    /**     * 当数据库创建时回调     *     * @param db 数据库对象     */    @Override    public void onCreate(SQLiteDatabase db) {        Log.i("----->", "------>onCreate");        String sql = "create table " + Constant.TABLE_NAME + "(" + Constant._ID + " Integer primary key autoincrement," + Constant.NAME + " varchar(10) ," + Constant.AGE + " Integer not null)";        db.execSQL(sql);//执行sql语句    }    /**     * 当数据库版本更新时回调     *     * @param sqLiteDatabase 数据库对象     * @param oldVersion     数据库旧版本     * @param newVerson      数据库新版本     */    @Override    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVerson) {        Log.i("----->", "------>onUpgrade");    }    /**     * 当数据库打开时调用     *     * @param db 数据库对象     */    @Override    public void onOpen(SQLiteDatabase db) {        super.onOpen(db);        Log.i("----->", "------>onOpen");    }}

为了使用方便,以及减少使用的耦合度我们一般是把一个Constant类来写我们信息:

public class Constant {    public static final String DATABASE_NAME = "info.db";//数据库名称    public static final int DAABASE_VERSION = 1;//数据库版本号    public static final String TABLE_NAME = "person";//表名    public static final String _ID = "_id";    public static final String NAME = "name";    public static final String AGE = "age";}
再一个呢为了方法使用,我们一般都会写一个工具类,使我们的代码就有一定的条理性:在这里我们就建立一个DbManger类:

public class DbManger  {    private static  MySqliteHelper helper;    public static  MySqliteHelper getIntance(Context context){         if (helper == null){             helper = new MySqliteHelper(context);         }        return  helper;    }    /**     * 根据sql语句在数据库中执行语句     * @param db 数据库对象     * @param sql sql语句     */    public static void execSQL(SQLiteDatabase db,String sql){        if (db!=null){            if (sql!=null && !"".equals(sql)) {                db.execSQL(sql);            }        }    }    /**     *查找数据     * @param db 数据库对象     * @param sql 要执行的sql语句     * @param selectionArgs     */    public static Cursor rawQuerySQL(SQLiteDatabase db,String sql,String[] selectionArgs){
Cursor cursor = null;        if (db!=null){            if (sql!=null && !"".equals(sql)) {                /**使用查找数据                 *rawQuery(String sql, String[] selectionArgs)                 * rawQuery(String sql, String[] selectionArgs, CancellationSignal cancellationSignal)                 * String sql 要执行的Sql语句                 * String[] selectionArgs                 * CancellationSignal cancellationSignal                 */                cursor = db.rawQuery(sql, selectionArgs);            }        }
    retuen cursor;    }}
然后呢就是我们我们的布局显示:在这里因为内容比较多所以我使用了一个Scrollview
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="match_parent"        android:orientation="vertical">        <Button            android:id="@+id/chuangjian"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:onClick="OnCerteDb"            android:text="创建数据库" />        <Button            android:id="@+id/btn_insert"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginTop="10dp"            android:onClick="click"            android:text="插入数据" />        <Button            android:id="@+id/btn_update"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginTop="10dp"            android:onClick="click"            android:text="修改数据" />        <Button            android:id="@+id/btn_delete"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginTop="10dp"            android:onClick="click"            android:text="删除数据" />        <Button            android:id="@+id/btn_select"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginTop="10dp"            android:onClick="click"            android:text="查询数据" />        <TextView            android:id="@+id/content"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:textSize="16sp"            android:layout_marginBottom="10dp"            android:layout_marginLeft="10dp"            android:layout_marginTop="20dp"/>        <View            android:layout_width="match_parent"            android:layout_height="2dp"            android:background="@android:color/darker_gray" />        <Button            android:id="@+id/btn_insertApi"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginTop="10dp"            android:onClick="OnClick"            android:text="插入数据API" />        <Button            android:id="@+id/btn_updateApi"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginTop="10dp"            android:onClick="OnClick"            android:text="修改数据API" />        <Button            android:id="@+id/btn_deleteApi"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginTop="10dp"            android:onClick="OnClick"            android:text="删除数据API" />        <TextView            android:id="@+id/contentapi"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:textSize="16sp"            android:layout_marginBottom="10dp"            android:layout_marginLeft="10dp"            android:layout_marginTop="20dp"/>    </LinearLayout></ScrollView>


最后就是我们的主要代码了 :

public class MainActivity extends AppCompatActivity {    private MySqliteHelper helper;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        helper = DbManger.getIntance(this);    }    public void OnCerteDb(View view) {        /**         * getReadableDatabase() getWritableDatabase() 创建或者打开数据库         * 如果数据不存在则创建数据库,如果数据存在则直接打开数据库         * 默认情况下两个都是表示打开或者创建一个可读可写的数据库对象,如果磁盘已满或者是数据库本事权限等情况下,getReadableDatabase()打开的是只读数据库         */        SQLiteDatabase db = helper.getWritableDatabase();    }    /**     * 使用sql语句的操作     *     * @param view     */    public void click(View view) {        switch (view.getId()) {            //插入数据            case R.id.btn_insert:                SQLiteDatabase db = helper.getWritableDatabase();                String sql = "insert into " + Constant.TABLE_NAME + " values(1,'zhangsan',20)";                Log.i("---->",sql);                DbManger.execSQL(db, sql);                String sql2 = "insert into " + Constant.TABLE_NAME + "(" + Constant._ID + "," + Constant.AGE + ") values(2,30)";                Log.i("---->",sql2);                DbManger.execSQL(db, sql2);                db.close();                break;            //修改数据            case R.id.btn_update:                db = helper.getWritableDatabase();                String updateSql = "update " + Constant.TABLE_NAME + " set " + Constant.NAME + "='张三' where " + Constant._ID + " =1";                Log.i("---->",updateSql);                DbManger.execSQL(db, updateSql);                db.close();                break;            //删除数据            case R.id.btn_delete:                db = helper.getWritableDatabase();                String deleteSql = "delete from " + Constant.TABLE_NAME + " where " + Constant._ID + "=1";                Log.i("---->",deleteSql);                DbManger.execSQL(db, deleteSql);                db.close();                break;            //查询数据            case R.id.btn_select:                db = helper.getWritableDatabase();                String selectSql = "select "+Constant.NAME+" from " + Constant.TABLE_NAME + "";                Log.i("---->",selectSql);                Cursor cursor= DbManger.rawQuerySQL(db, selectSql, null);                while (cursor.moveToNext()) {                    String name =cursor.getString(0);                    Log.i("---->"," name:"+name);//                    String name=cursor.getString(1);//                    int age=cursor.getInt(2);//                    Log.i("---->","id:"+id+" name:"+name+" age:"+age);                }                cursor.close();                db.close();                break;        }    }    /**     * 使用sqlAPI的操作     *     * @param view     */    public void OnClick(View view) {        switch (view.getId()) {            //使用api添加数据            case R.id.btn_insertApi:                SQLiteDatabase db = helper.getWritableDatabase();                /**使用db.insert()方法                 * insert(String table, String nullColumnHack, ContentValues values)                 * String table 表示插入数据表的名称                 *  String nullColumnHack                 * ContentValues values  表示一个键为String类型的hashmap集合                 * 返回值 long 表示插入数据的列数                 */                ContentValues values = new ContentValues();                values.put(Constant._ID, 3);//put(表示插入数据库的字段名称,表示插入该字段的具体值)                values.put(Constant.NAME, "王麻子");                values.put(Constant.AGE, 35);                long insert = db.insert(Constant.TABLE_NAME, null, values);                if (insert > 0)                    Toast.makeText(this, "插入数据成功", Toast.LENGTH_SHORT).show();                else                    Toast.makeText(this, "插入数据失败", Toast.LENGTH_SHORT).show();                db.close();                break;            //使用api修改数据            case R.id.btn_updateApi:                db = helper.getWritableDatabase();                /**使用db.pudate()方法                 * update(String table, ContentValues values, String whereClause, String[] whereArgs)                 * String table 表示修改数据表的名称                 * ContentValues values  表示一个键为String类型的hashmap集合                 * String whereClause  表示修改条件                 * String[] whereArgs 表示修改条件的占位符                 * 返回值 int 表示修改的条数                 */                ContentValues apivalues = new ContentValues();                apivalues.put(Constant.AGE, 100);//put(需要修改的字段名称,修改的对应新值)                int update = db.update(Constant.TABLE_NAME, apivalues, Constant._ID + "=3", null);//或者db.update(Constant.TABLE_NAME,apivalues,Constant._ID+"=?",new String[] {"3"});                if (update > 0)                    Toast.makeText(this, "修改数据成功", Toast.LENGTH_SHORT).show();                else                    Toast.makeText(this, "修改数据失败", Toast.LENGTH_SHORT).show();                db.close();                break;            //使用api删除数据            case R.id.btn_deleteApi:                db = helper.getWritableDatabase();                /**                 * int delete(String table, String whereClause, String[] whereArgs)                 *String table 表示数据库表名                 * String whereClause 表示删除条件                 * String[] whereArgs 表示 删除条件的占位符                 */                int delete = db.delete(Constant.TABLE_NAME, Constant._ID + "=3", null);//或者是db.delete(Constant.TABLE_NAME,Constant._ID+"=?",new String []{"3"});                if (delete > 0)                    Toast.makeText(this, "删除数据成功", Toast.LENGTH_SHORT).show();                else                    Toast.makeText(this, "删除数据失败", Toast.LENGTH_SHORT).show();                db.close();                break;        }    }}

Demo下载:下载好用Demo哦







0 0
原创粉丝点击