Android development tutorial --- SQLite data storage

Today we mainly use to say something about SQLite in Android's.

      Easily follows:

      Offices in office buildings, offices of programmers;
     programmers write programs, exchange programs and took the drinks.
     Online only take sober, drunk also to sleep under the net;
     the drunken sober day after day, year after year online and offline.
     Hopefully between computers die of old age, I do not want to bow before the boss;
     Mercedes-Benz BMW's your interest, public transportation on their own programmers.
     Intuit insane people laugh at me, I laugh at my life too cheap;
     see the streets pretty girl, which was owned by the programmer. :) Hey…

      SQLite Introduction

      Most applications have to manipulate data ,, Android applications are no exception, local data should be stored somewhere? Android uses open source, operating system-independent SQL database - the famous SQLite. SQLite is a lightweight database, it is designed to be embedded, and it takes very few resources in embedded devices, only a few hundred KB , many large companies developed the product has its existence.

    Lightweight
   using SQLite just need to bring a dynamic library, you can enjoy all its functions, and the size of the dynamic library is quite small.

   The independence of the
   SQLite database engine does not need to rely on third-party software core, does not need the so-called "Install."

   Isolation
   SQLite database all information (such as tables, views, triggers, etc.) are contained in a folder for easy management and maintenance.

   Cross-platform
   SQLite currently supports most operating systems, not just the computer operating system is also able to run many more mobile phone systems such as: Android.

   Multi-language interface to
   the SQLite database supports multilingual programming interface.

   Security
   SQLite database transaction processing to achieve independence through exclusive and shared locks on the database level. This means that multiple processes can read data from the same database at the same time, but only one can write data.

   SQLite although very small, but does not support SQL statements inferior to other open source database that supports SQL include:

   1

Sqlite basic data types:

VARCHAR character

NVARCHAR (15) varying character,

TEXT text type,

INTEGER integer,

FLOAT float,

BOOLEAN boolean,

CLOB Character Large Object,

BLOB Binary Large Objects,

TIMESTAMP date type,

NUMERIC (10,5) Numeric

VARYING CHARACTER (24),

NATIONAL VARYING CHARACTER(16)

Sqlite also provides a JDBC driver

Class.forName("org.sqlite.JDBC");

Connection conn = DriverManager.getConnection("jdbc:sqlite:filename");

// filename is the name of your SQLite data

Database operations using SQLiteOpenHelper

getReadableDatabase () obtained readable SQLiteDatabase

getWritableDatabase () obtain written SQLiteDatabase

onCreate(SQLiteDatabase)

onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion)

onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)

Database operations

1. SQLite a packaging operations of the class, and in this way to achieve using inheritance SQLiteOpenHelper

SQLiteOpenHelper
SQLiteOpenHelper is an abstract class, to create and manage versions of the database management. To use it you must implement it

onCreate(SQLiteDatabase),

onUpgrade (SQLiteDatabase, int, int) method
onCreate: to be executed when the database was first established, such as creating tables, initialization data.
onUpgrade: When the database needs to be updated to perform, such as deleting a long table, create a new table.

2. To achieve SQLiteOpenHelper class constructor and abstract methods.

Copy the code
package TSD.Jason.DB;

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

public class DBHelp extends SQLiteOpenHelper {

private final static String DATABASE_NAME="StudentDB"; //数据库名称
private final static int DATABASE_VERSION=1; //数据库默认版本
private final static String TABLE_NAME="StudentInfo"; //数据表名称publicfinalstatic String S_ID="sid"; // 列名publicfinalstatic String S_NAME="sName"; publicfinalstatic String S_SEX="sSex"; publicfinalstatic String S_AGE="sAge";publicfinalstatic String S_ADDRESS="sAddress";context context object@param * * This constructor is used to create a library and a table (the first execution, if there is no library, table, create databases, tables, not later re-creation) *Constructor SQLiteOpenHelper class (Note: The constructor must be implemented)/ **










*
@Param name the name of the database
*
@param Factory's creation Cursor factory class. Parameters can be customized to create Cursor
*
@param Version database version
* /
public DBHelp (the Context context, String name, CursorFactory Factory,
int Version) {
Super (context, name, Factory, Version);

}

/ ** operational data when, (CRUD)
*
*
@param context context object
*
@param name the name of the database
*
@param factory's creation Cursor factory class. You can customize the parameters to create Cursor
*
@param Version database version number
* /
publicDBHelp (the Context context) {
the this (context, DATABASE_NAME, null , database_version);
}

/ ** required to implement modified according to the version
*
* This constructor is used to modify the database and tables (modify existing databases, tables)
*
@ param context the context object
*
@param name the name of the database
*
@param factory's creation Cursor factory class. Parameters can be customized to create Cursor
*
@param Version database version
* /
public DBHelp (the Context context, int Version) {
the this (context, DATABASE_NAME, null , Version);
}

@Override
public voidthe onCreate (the SQLiteDatabase DB) {
// the TODO Auto-Generated Stub Method
System.out.println ( "when first run or modify the database, will automatically execute");

String createTableSQL = "Create Table" + + TABLE_NAME "( "
+ S_ID, +" Integer Primary Key AUTOINCREMENT, "
+ S_NAME +" nvarchar (10), "
+ S_SEX +" nvarchar (2), "
+ S_AGE +" int, "
+ S_ADDRESS +" nvarchar (50) "
+") ";
db.execSQL (createTableSQL);// execute SQL requires the use of execSQL ()
}

@Override
public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {
System.out.println ( "------------------------- called a modified library function ");

}

@Override
public void the onOpen (the SQLiteDatabase DB) {
// the TODO Auto-Generated Method Stub Super .onOpen (DB); System.out.println (" when the database is opened, performed "); } }






Copy the code

 

Create a database

DbHelp = DBHelp new new DBHelp (SQLiteActivity. The this ); 
// when received SQLiteDatabase object will automatically detect whether you first create a database, table, if not the execution DBHelp class onCreate function
SQLiteDatabase db = dbHelp.getReadableDatabase () ;
Toast.makeText (. SQLiteActivity the this , "successfully created", Toast.LENGTH_SHORT) .show ();

 

getWritableDatabase () operation if needed (CRUD) database,

getReadableDatabase () query data

Delete and rename the database

2

 

 

View the database in adb

 3

1 query directory structure for the ls command

2 corresponding to the file into the folder name by folder cd

3 need to enter data twice folder

4 into the package to create a project of their own under

5 into the databases

6 access to databases sqlite3 StudentDB

Enter at sqlite> prompt

.help This command allows us to see a lot of command

.tables see all the tables

By .tables command, you can query this database to all table names

And in the same query SQLServer, ending each sentence Sql statements require the semicolon;

adding data

Copy the code
btn5.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {

DBHelp dbHelp = new DBHelp(SQLiteActivity.this);
SQLiteDatabase db = dbHelp.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("sName", txtName.getText().toString());
contentValues.put("sSex", "男");
if(dbHelp.InsertData(db, contentValues))
Toast.makeText(SQLiteActivity.this, "添加成功", Toast.LENGTH_SHORT).show();
else
Toast.makeText(SQLiteActivity.this, "添加失败", Toast.LENGTH_SHORT).show();
}
});
Copy the code

修改数据

Copy the code
btn6.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {

DBHelp dbHelp = new DBHelp(SQLiteActivity.this);
SQLiteDatabase db = dbHelp.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("sName", txtsName.getText().toString());
String whereClause = "sid=?"; //要修改数据的条件 值用?占位符
String[] whereArgs = new String[]{txtsID.getText().toString()};
if(dbHelp.UpdateData(db, contentValues, whereClause, whereArgs))
Toast.makeText(SQLiteActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
else
Toast.makeText(SQLiteActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
}
});
Copy the code

删除数据

Copy the code
    btn7.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {

DBHelp dbHelp = new DBHelp(SQLiteActivity.this);
SQLiteDatabase db = dbHelp.getWritableDatabase();
String whereClause = "sid=?"; //要删除数据的条件 值用?占位符
String[] whereArgs = new String[]{txtID.getText().toString()};
if(dbHelp.DeleteData(db, whereClause, whereArgs))
Toast.makeText(SQLiteActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
else
Toast.makeText(SQLiteActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
}
});
Copy the code

查询数据

rawQuery()

rawQuery() 是最简单的解决方法。例如:

Cursor c=db.rawQuery(
“SELECT * FROM Student WHERE sid=1 AND sname=‘zhangsan'", null);

query()

都会返回一个 Cursor,这是 Android 的 SQLite 数据库游标

操作游标

 

通过使用 getCount() 方法得到结果集中有多少记录;
通过 moveToFirst(), moveToNext(), 和 isAfterLast() 方法遍历所有记录;
通过 getColumnNames() 得到字段名;
通过 getColumnIndex() 转换成字段号;
通过 getString(),getInt() 等方法得到给定字段当前记录的值;
通过 requery() 方法重新执行查询得到游标;
通过 close() 方法释放游标资源;
SimpleCursorAdapter
SimpleCursorAdapter
可使用此类来绑定ListView 

SimpleCursorAdapter simple = new SimpleCursorAdapter(SQLiteActivity.this, android.R.layout.simple_list_item_1, cur, new String[]{"sName","sSex"}, new int[]{android.R.id.text1,android.R.id.text2});

studentList.setAdapter(simple);

注意: 使用此类绑定数据,,必须注意sqlite的主键命名。由于simpleCursorAdapter的方法只识别_id,所以,当你用到sqlite的 simpleCursorAdapter时,必须把数据表的主键命名为_id。否则就会出现 java.lang.IllegalArgumentException: column ‘_id’ does not exist 错误。

 查询数据
Copy the code
public void BinderData(){
DBHelp dbHelp = new DBHelp(SQLiteActivity.this);
SQLiteDatabase db = dbHelp.getReadableDatabase();
/*参数
* table 表名
* columns 要查询的列名数组,所有列用 null
* selection 要查询的条件 没有用null
* selectionArgs 要查询的条件对应的值 没有用null
* groupBy 分组 没有用null
* having 分组后再次筛选 没有用null
* orderBy 排序 没有用null
*
*/
Cursor cur = db.query("StudentInfo", null, null, null, null, null, null);
//Cursor cur = db.rawQuery("select * from StudentInfo", null);

//由于本例中使用的主键名不是_id 所以不能直接使用SimpleCursorAdapter 原因在PPT中已经做了说明
//SimpleCursorAdapter simple = new SimpleCursorAdapter(SQLiteActivity.this, android.R.layout.simple_list_item_1, cur, new String[]{"sName","sSex"}, new int[]{android.R.id.text1,android.R.id.text2});
//studentList.setAdapter(simple);
ArrayList<HashMap<String, Object>> students = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> hs ;
for (cur.moveToFirst();!cur.isAfterLast();cur.moveToNext()) {
System.out.println(cur.getInt(cur.getColumnIndex("sid"))+"aaaaaaaaa");
hs = new HashMap<String, Object>();
hs.put("sID", cur.getInt(cur.getColumnIndex("sid")));
hs.put("sName", cur.getString(cur.getColumnIndex("sName")));
hs.put("sSex", cur.getString(cur.getColumnIndex("sSex")));
students.add(hs);
}
SimpleAdapter sim = new SimpleAdapter(SQLiteActivity.this, students, android.R.layout.simple_list_item_1, new String[]{"sName","sSex"}, new int[]{android.R.id.text1,android.R.id.text2});
studentList.setAdapter(sim);
}

Reproduced in: https: //www.cnblogs.com/Codenewbie/archive/2013/03/21/2973259.html

Guess you like

Origin blog.csdn.net/weixin_33852020/article/details/93448204