加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

SQLite用法

发布时间:2020-12-13 00:01:42 所属栏目:百科 来源:网络整理
导读:SQLiteDataBase是数据库类, SQLiteOpenHelper是用来管理数据库的辅助类 一,SQLiteOpenHelper 类 其中 : getReadableDatabase()得到可读的数据库,返回SQLiteDatabase对象,然后通过对象进行数据库操作。 getWritableDatabase()得到可写的数据库,返回SQLi
The table name to compile the query against.(要查询的表名.) A list of which columns to return. Passing null will return allcolumns,which is discouraged to prevent reading data from storagethat isn't going to be used.(想要显示的列,若为空则返回所有列,不建议设置为空,如果不是返回所有列) A filter declaring which rows to return,formatted as an SQL WHEREclause (excluding the WHERE itself). Passing null will return allrows for the given table.(where子句,声明要返回的行的要求,如果为空则返回表的所有行。) You may include ?s in selection,which will be replaced by thevalues from selectionArgs,in order that they appear in theselection. The values will be bound as Strings.(where子句对应的条件值) A filter declaring how to group rows,formatted as an SQL GROUP BYclause (excluding the GROUP BY itself). Passing null will cause therows to not be grouped.(分组方式,若为空则不分组.) A filter declare which row groups to include in the cursor,if rowgrouping is being used,formatted as an SQL HAVING clause(excluding the HAVING itself). Passing null will cause all rowgroups to be included,and is required when row grouping is notbeing used.(having条件,若为空则返回全部(不建议)) How to order the rows,formatted as an SQL ORDER BY clause(excluding the ORDER BY itself). Passing null will use the defaultsort order,which may be unordered.(排序方式,为空则为默认排序方式) Limits the number of rows returned by the query,formatted as LIMITclause. Passing null denotes no LIMIT clause.(限制返回的记录的条数,为空则不限制)
Returns
  • ACursorobject,which is positioned before the first entry. NotethatCursorsare not synchronized,see the documentation for more details.
示例:ContentValues cv =newContentValues();String[] args = {String.valueOf("a")};

query("user",new String[] {"username","password"},monospace; color:#2a00ff; line-height:15px; text-align:left">"username=?"argsnull,null);


2、SQLiteDataBase对象的insert()接口:

publiclonginsert(Stringtable,StringnullColumnHack,ContentValuesvalues)

Convenience method forinserting a row into the database.

Parameters
the table to insert the row into(要插入数据的表的名称) optional; may benull.SQL doesn't allow inserting a completely empty row without namingat least one column name. If yourprovidedvaluesisempty,no column names are known and an empty row can't beinserted. If not set to null,thenullColumnHackparameterprovides the name of nullable column name to explicitly insert aNULL into in the case where yourvaluesisempty.(当values参数为空或者里面没有内容的时候,我们insert是会失败的(底层数据库不允许插入一个空行),为了防止这种情况,我们要在这里指定一个列名,到时候如果发现将要插入的行为空行时,就会将你指定的这个列名的值设为null,然后再向数据库中插入。) this map contains the initial column values for the row. The keysshould be the column names and the values the columnvalues(一个ContentValues对象,类似一个map.通过键值对的形式存储值。)
Returns
  • the row ID of the newly insertedrow,or -1 if an error occurred
示例:ContentValues();cv.put("username","a");"password""b" ); insert("user", null 3、SQLiteDataBase对象的update()接口:

publicintupdate(Stringtable,ContentValuesvalues,StringwhereClause,String[]whereArgs)

Convenience method for updatingrows in the database.

Parameters
the table to update in(要更新的表名) a map from column names to new column values. null is a valid valuethat will be translated to NULL.(一个ContentValues对象,类似一个map.通过键值对的形式存储值。) the optional WHERE clause to apply when updating. Passing null willupdate all rows.(可选的where语句)

the group of args to dealwith(whereClause语句中表达式的?占位参数列表
)
Returns
  • the number of rows affected
ContentValues(); cv.put("username""c" ); "password""d" ); String[] args = {String.valueOf( "a" )}; update("user",cv,"username=?"4、SQLiteDataBase对象的delete()接口: publicintdelete(Stringtable,String[]whereArgs)

Convenience method for deletingrows in the database.

Parameters
the table to delete from the optional WHERE clause to apply when deleting. Passing null willdelete all rows.(可选的where语句)
the optional WHERE clauseto apply when updating. Passing null will update allrows.(whereClause语句中表达式的?占位参数列表)
Returns
  • the number of rows affected if awhereClause is passed in,0 otherwise. To remove all rows and get acount pass "1" as the whereClause.
示例: ContentValues(); String[] args = {String.valueOf( "c" )}; delete("username=?" ,args);



SQLiteOpenHelper:是一个辅助类,这个类主要用于生产一个数据库,并对数据库的版本进行管理。此类为一抽象类,使用是需要继承此类并实现该类的方法
onCreate(SQLiteDatabase):在数据库第一次生产的时候会调用这个方法,一般我们在这个方法里边生产数据库表。
onUpgrade(SQLiteDatabase,int,int):当数据库需要升级的时候,Android系统会主动的调用这个方法。一般我们在这个方法里边删除数据库表,并建立新的数据库表,当然是否还需要做其他的操作,完全取决于应用程序的需求。
onOpen(SQLiteDatabase):这是当打开数据库时的回调函数,一般也不会用到。

调用程序方法返回SQLiteDatabase对象。
当在程序当中调用这个类的方法getWritableDatabase()或者getReadableDatabase()方法的时候,如果当时没有数据,那么Android系统就会自动生产一个数据库。数据库使用完后记得调用close()方法关闭数据库。


创建数据库类:
Java代码
  1. publicclassDatabaseHelperextendsSQLiteOpenHelper{
  2. privatestaticfinalStringTABLE_NAME="itss";//数据库名称
  3. privatestaticfinalintversion=1;//数据库版本
  4. privateStringTITLE="title";
  5. privateStringBODY="body";
  6. publicDatabaseHelper(Contextcontext){
  7. super(context,TABLE_NAME,version);
  8. //TODOAuto-generatedconstructorstub
  9. }
  10. @Override
  11. publicvoidonCreate(SQLiteDatabasedb){
  12. Stringsql="createtable"+TABLE_NAME+"("+TITLE+"textnotnull,"+BODY+"textnotnull);";
  13. Log.i("haiyang:createdb=",sql);
  14. db.execSQL(sql);
  15. }
  16. @Override
  17. publicvoidonUpgrade(SQLiteDatabasedb,intnewVersion){
  18. //TODOAuto-generatedmethodstub
  19. }
  20. }


调用方法:
Java代码
  1. DatabaseHelperdatabase=newDatabaseHelper(this
  2. .getApplicationContext());
  3. Log.i("haiyang:createdb=","执行失败");
  4. SQLiteDatabasedb=null;
  5. try
  6. {
  7. db=database.getWritableDatabase();
  8. }
  9. catch(SQLiteExceptionex)
  10. db=database.getReadableDatabase();
  11. }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

SQLiteDataBase是数据库类,SQLiteOpenHelper是用来管理数据库的辅助类

一,SQLiteOpenHelper 类

其中

getReadableDatabase()得到可读的数据库,返回SQLiteDatabase对象,然后通过对象进行数据库操作。

getWritableDatabase()得到可写的数据库,返回SQLiteDatabase对象,然后通过对象进行数据库操作。

onCreate(SQLiteDatabase db)在第一次创建数据库时调用。

onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion)在更改数据库时都会调用。

onOpen(SQLiteDatabase db)当数据库打开时调用。

close()关闭数据库。

二,SQLiteDatabase类

这个类提供了对数据库的一些基本操作:

insert()

delete()

update()

query()

。。。。。等等。

代码:

SQLiteOpenHelper 的子类:

[java] view plain copy
  1. importandroid.content.Context;
  2. importandroid.database.sqlite.SQLiteDatabase;
  3. importandroid.database.sqlite.SQLiteDatabase.CursorFactory;
  4. importandroid.database.sqlite.SQLiteOpenHelper;
  5. /**
  6. *通过getReadableDatabase()和getWritableDatabase()可以获得数据库对象。
  7. *提供onCreate()-创建数据库时,onUpgrade()-升级数据库时,两个回调函数。
  8. */
  9. publicclassDatabaseHelperextendsSQLiteOpenHelper{
  10. //按要求必须要有构造函数
  11. publicDatabaseHelper(Contextcontext,Stringname,CursorFactoryfactory,
  12. intversion){
  13. super(context,name,factory,version);
  14. }
  15. //当第一次得到SQLiteDatabase对象时,调用该方法
  16. @Override
  17. publicvoidonCreate(SQLiteDatabasedb){
  18. Stringsql="createtableMSG(idint,bodyvarchar(100))";
  19. db.execSQL(sql);
  20. System.out.println("创建了一个数据库!");
  21. }
  22. //当更新数据库时执行该方法
  23. @Override
  24. publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){
  25. System.out.println("更新了数据库!");
  26. //还可以写其他的操作
  27. }
  28. }

有了这个类后,我们就可以对数据库进行增、删、改、查操作了。
插入数据:

[java] view plain copy
  1. //生成ContentValues对象,key:列名,value:想插入的值
  2. ContentValuesvalues=newContentValues();
  3. values.put("id",1);
  4. values.put("body","hello");
  5. DatabaseHelperdbhelper=newDatabaseHelper(SqliteActivity.this,"text_msg",null,2);
  6. //得到可写的SQLiteDatabase对象
  7. SQLiteDatabasedb=dbhelper.getWritableDatabase();
  8. //调用insert方法,将数据插入数据库
  9. //参数1:表名
  10. //参数2:如果你想插入空值,那么你必须指定它的所在的列
  11. db.insert("MSG",values);
  12. System.out.println("插入了:1,hello");

删除数据:

[java] view plain copy
  1. DatabaseHelperdbhelper=newDatabaseHelper(SqliteActivity.this,2);
  2. //得到可写的SQLiteDatabase对象
  3. SQLiteDatabasedb=dbhelper.getWritableDatabase();
  4. //调用delete方法,删除数据
  5. db.delete("MSG","id=?",newString[]{"1"});
  6. System.out.println("删除了:id=1");

修改数据:

[java] view plain copy
  1. ContentValuesvalues=newContentValues();
  2. values.put("body","mydear!");
  3. DatabaseHelperdbhelper=newDatabaseHelper(SqliteActivity.this,2);
  4. //得到可写的SQLiteDatabase对象
  5. SQLiteDatabasedb=dbhelper.getWritableDatabase();
  6. //调用insert方法,将数据插入数据库
  7. //参数3:where子句"?"是占位符号,对应后面的"1",这和web开发时的语法是一样的
  8. db.update("MSG",values,newString[]{"1"});
  9. System.out.println("更新了:hello-->mydear!");

查询数据:

2);
  • //得到可读的SQLiteDatabase对象
  • SQLiteDatabasedb=dbhelper.getReadableDatabase();
  • //参数1:表名
  • //参数2:要想显示的列
  • //参数3:where子句
  • //参数4:where子句对应的条件值
  • //参数5:分组方式
  • //参数6:having条件
  • //参数7:排序方式
  • Cursorcursor=db.query("MSG",newString[]{"id","body"},newString[]{"1"},null);
  • System.out.println("查到的数据为:");
  • while(cursor.moveToNext()){
  • intid=cursor.getInt(cursor.getColumnIndex("id"));
  • Stringname=cursor.getString(cursor.getColumnIndex("body"));
  • System.out.println("-->"+id+"::::::::::"+name);
  • }


  • 1、SQLiteDataBase对象的query()接口: publicCursor query (Stringtable,String[]columns,Stringselection,String[]selectionArgs,                               StringgroupBy,Stringhaving,StringorderBy,Stringlimit)

    Query the given table,returning aCursoroverthe result set.

    Parameters
    table columns selection selectionArgs groupBy having orderBy limit
    table nullColumnHack values
    table values whereClause


    whereArgs
    table whereClause

    whereArgs