SQLite本身就是一個獨立的第三方庫,包含2T的容量,有自己的語法,Android集成了SQlite數(shù)據庫。
SQLite中的數(shù)據類型 有五種儲存類型
NULL 空
INTEGER 整型
REAL 浮點型
TEXT 文本
BLOB 普通數(shù)據
Android中獲取數(shù)據庫對象:
SQLiteDatebase db= myOpenHelper.getWriteableDatebase();
//如果磁盤內存未滿著調用getWritableDatabase(),如果磁盤內存滿了,就用只讀模式開啟數(shù)據庫 SQLiteDatabase
db = mySQLite.getReadableDatabase();
SQLite數(shù)據庫主要包含了:增、刪、改、查, 四個方面
在Android中主要有兩種方式來實現(xiàn)SQLite數(shù)據庫的,增、刪、改、查
提供一個幫助類SQLiteOpenHelper,用自己實現(xiàn)類繼承即可
第一種———是使用SQLite語句來實現(xiàn):
分別調用:
db.execSQL (SQLite語句,?數(shù)據集合)
db.rawQuery(SQLite語句,?數(shù)據集合)
所以SQLite可以解析大部分標準SQL語句,如:
查詢語句: select * from 表名 where 條件子句 group by 分組字句 having ...order by 排序子句
如:select * from person
select * from person order by id desc
selsct name from person group bu name having count(*)>1
分頁SQL與mysql類型,下面SQL語句獲取5條記錄,跳轉前面3條記錄
select * from Account limit 5offset 3 或者 select * from Account limit 3,5
插入語句:insert into 表名 (字段列表) values (值列表)。如: insert into person (name,age) values ('快發(fā)' , 3)
更新語句:update 表名 set 字段名=值 where 條件子句。如:update person ser name='快發(fā)' where id = 10
刪除語句:delete from 表名 where 條件子句。如:delete from person where id= 10
獲取添加記錄后自增長的ID值: SELECT last_insert_rowid( )
第二種——是使用Android提供的API實現(xiàn):
insert() 它接收三個參數(shù),第一個參數(shù)是表名,我們希望向哪張表里添加數(shù)據,這里就傳入該表的名字。
第二個參數(shù)用于在未指定添加數(shù)據的情況下給某些可為空的列自動賦值 NULL,一般我們用不到這個功能,
直接傳入 null 即可。第三個參數(shù)是一個 ContentValues 對象,它提供了一系列的 put()方法重載,用于向
ContentValues 中添加數(shù)據,只需要將表中的每個列名以及相應的待添加數(shù)據傳入即可.
update() 這個方法接收四個參數(shù),第一個參數(shù)和 insert()方法一樣,也是表名,在這里指定去更新哪張表里的數(shù)據。第二個參數(shù)是
ContentValues 對象,要把更新數(shù)據在這里組裝進去。第三、第四個參數(shù)用于去約束更新某一行或某幾行中的數(shù)據,不指定的話默認就是更新所有行。
delete() 這個方法接收三個參數(shù),第一個參數(shù)仍然是表名,這個已經沒什么好說的了,第二、第三個參數(shù)又是用于去約束刪除某一
行或某幾行的數(shù)據,不指定的話默認就是刪除所有行。
query() 第一個參數(shù)不用說,當然還是表名,表示我們希望從哪張表中查詢數(shù)據。
第二個參數(shù)用于指定去查詢哪幾列,如果不指定則默認查詢所有列。
第三、第四個參數(shù)用于去約束查詢某一行或某幾行的數(shù)據,不指定則默認是查詢所有行的數(shù)據。
第五個參數(shù)用于指定需要去 group by 的列,不指定則表示不對查詢結果進行 group by 操作。
第六個參數(shù)用于對 group by 之后的數(shù)據進行進一步的過濾,不指定則表示不進行過濾。
第七個參數(shù)用于指定查詢結果的排序方式,不指定則表示使用默認的排序方式。
幫助類MySQLite代碼:
package com.example.administrator.foundationdemo.sqlite.service;
import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created by Administrator on 2016/12/12.
*/
public class MySQLite extends SQLiteOpenHelper{
public MySQLite (Context context,String name){//保存路徑 <包>/datebases/
this(context,name,null,2);
}
public MySQLite(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public MySQLite(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
super(context, name, factory, version, errorHandler);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {//數(shù)據庫第一次被創(chuàng)建時調用
//創(chuàng)建表 表名稱 自增長ID名
sqLiteDatabase.execSQL("CREATE TABLE person (personId integer primary key autoincrement,name varchar(20))");
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {//版本號發(fā)生修改時調用
//給表增加已給字段
sqLiteDatabase.execSQL("ALTER TABLE person ADD phone VARCHAR(12) NULL");
}
}
操作類PersonSQLite代碼:
package com.example.administrator.foundationdemo.sqlite.service;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;
import com.example.administrator.foundationdemo.sqlite.domain.Person;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2016/12/12.
*/
public class PersonSQLite {
private MySQLite mySQLite;
private Context context;
public PersonSQLite(Context context){
this.context = context;
mySQLite = new MySQLite(context,"mySQLite");
}
//增
public void save(Person person){
SQLiteDatabase db = mySQLite.getWritableDatabase();
/**
* 方法一:Androiod集成API,用于SQLite數(shù)據庫增加數(shù)據
*/
// ContentValues values = new ContentValues();
// //參數(shù)鍵 值
// values.put("name",person.getName());
// values.put("phone",person.getPhone());
// //表名 參數(shù)集合
// db.insert("person",null,values);//NULL值字段,及可以為空的字段,如果db.insert("person","name",null);及name為NULL不會報錯,如果均為空著會報錯
/**
* 方法二:execSQL,SQLite 語句添加,可練習SQLite語句的熟練度
*/
//增加的SQLite語句 根據前面問號順序排列的值
db.execSQL("insert into person (name,phone) values (?,?)",new Object[]{person.getName(),person.getPhone()});
db.close();//關閉數(shù)據庫
}
//刪
public void delete(Integer id){
SQLiteDatabase db = mySQLite.getWritableDatabase();
/**
* 方法一:Androiod集成API,用于SQLite數(shù)據刪除數(shù)據
*/
// db.delete("person","personId=?",new String[]{id.toString()});
/**
* 方法二:execSQL,SQLite 語句刪除,可練習SQLite語句的熟練度
*/
db.execSQL("delete from person where personId=?",new Object[]{id});
db.close();//關閉數(shù)據庫
}
//改
public void update(Person person){
SQLiteDatabase db = mySQLite.getWritableDatabase();
/**
* 方法一:Androiod集成API,用于SQLite數(shù)據庫更新數(shù)據
*/
// ContentValues values = new ContentValues();
// //參數(shù)鍵 值
// values.put("name",person.getName());
// values.put("phone",person.getPhone());
// db.update("person", values, "personId=?", new String[]{person.getId()+""});
/**
* 方法二:execSQL,SQLite 語句更新,可練習SQLite語句的熟練度
*/
db.execSQL("update person set name=?,phone=? where personId=?",new Object[]{person.getName(),person.getPhone(),person.getId()});
db.close();//關閉數(shù)據庫
}
//查
public Person find(Integer id){
SQLiteDatabase db = mySQLite.getReadableDatabase();//如果磁盤內存未滿著調用getWritableDatabase(),如果磁盤內存滿了,就用只讀模式開啟數(shù)據庫
/**
* 方法一:Androiod集成API,用于SQLite數(shù)據庫查找數(shù)據
*/
//數(shù)據集合null及全部
// db.query("person",null, "personId=?", new String[]{id.toString()},null,null,null);
/**
* 方法二:execSQL,SQLite 語句查找,可練習SQLite語句的熟練度
*/
Cursor cursor = db.rawQuery("select * from person where personId=?", new String[]{id.toString()});//獲得游標
if (cursor.moveToFirst()){//判斷數(shù)據是否存在
int personId = cursor.getInt(cursor.getColumnIndex("personId"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String phone = cursor.getString(cursor.getColumnIndex("phone"));
cursor.close();
return new Person(personId,name,phone);
}else {
cursor.close();
Toast.makeText(context,"數(shù)據不存在!",Toast.LENGTH_SHORT).show();
return null;
}
}
//分頁查詢
public List<Person> getScrollDate(int offset,int maxResult){
List<Person> list = new ArrayList<Person>();
SQLiteDatabase db = mySQLite.getReadableDatabase();//如果磁盤內存未滿著調用getWritableDatabase(),如果磁盤內存滿了,就用只讀模式開啟數(shù)據庫
/**
* 方法一:Androiod集成API,用于SQLite數(shù)據庫查找數(shù)據
*/
// db.query("person",null,null ,null,null,"personId asc",offset+","+maxResult);
/**
* 方法二:execSQL,SQLite 語句查找,可練習SQLite語句的熟練度
*/
//將數(shù)據庫表person按personId升序排列在分頁 asc|desc ==>升序|降序
Cursor cursor = db.rawQuery("select * from person order by personId asc limit ?,?", new String[]{String.valueOf(offset),String.valueOf(maxResult)});
while (cursor.moveToNext()){//移動游標
int personId = cursor.getInt(cursor.getColumnIndex("personId"));
String name = cursor.getString(cursor.getColumnIndex("name"));
String phone = cursor.getString(cursor.getColumnIndex("phone"));
list.add(new Person(personId,name,phone));
}
cursor.close();//關閉指針
return list;
}
//統(tǒng)計數(shù)據庫記錄
public long getCount(){
SQLiteDatabase db = mySQLite.getReadableDatabase();//如果磁盤內存未滿著調用getWritableDatabase(),如果磁盤內存滿了,就用只讀模式開啟數(shù)據庫
/**
* 方法一:Androiod集成API,用于SQLite數(shù)據庫查找數(shù)據
*/
// db.query("person",new String[]{"count(*)"},null ,null,null,null,null);
/**
* 方法二:execSQL,SQLite 語句查找,可練習SQLite語句的熟練度
*/
//將數(shù)據庫表person按personId升序排列在分頁
Cursor cursor = db.rawQuery("select count(*) from person ", null);
cursor.moveToFirst();
long result = cursor.getLong(0);
cursor.close();
return result;
}
}
實例類person代碼:
package com.example.administrator.foundationdemo.sqlite.domain;
/**
* Created by Administrator on 2016/12/12.
*/
public class Person {
private int id;
private String name;
private String phone;
public Person(){
}
public Person(String name, String phone) {
this.name = name;
this.phone = phone;
}
public Person(int id, String name, String phone) {
this.id = id;
this.name = name;
this.phone = phone;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
測試Activity代碼:
package com.example.administrator.foundationdemo.sqlite;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.administrator.foundationdemo.R;
import com.example.administrator.foundationdemo.sqlite.domain.Person;
import com.example.administrator.foundationdemo.sqlite.service.MySQLite;
import com.example.administrator.foundationdemo.sqlite.service.PersonSQLite;
import java.util.List;
public class SQLiteActivity extends AppCompatActivity {
private EditText person_name_edittext;
private EditText person_phone_edittext;
private EditText person_id_edittext;
private EditText person_num1_edittext;
private EditText person_num2_edittext;
private TextView text;
private PersonSQLite personSQLite;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sqlite);
init();
}
public void onClick(View view){
switch (view.getId()){
case R.id.save_sql_button:
personSQLite.save(new Person(person_name_edittext.getText().toString(),person_phone_edittext.getText().toString()));
break;
case R.id.delete_sql_button:
String personId = person_id_edittext.getText().toString();
if (null == personId||"".equals(personId)){
person_id_edittext.setVisibility(View.VISIBLE);
person_id_edittext.setHint("請輸入刪除personId");
}else {
personSQLite.delete(Integer.parseInt(personId));
person_id_edittext.setText("");
person_id_edittext.setVisibility(View.GONE);
}
break;
case R.id.update_sql_button:
break;
case R.id.find_sql_button:
String personId1 = person_id_edittext.getText().toString();
if (null == personId1||"".equals(personId1)){
person_id_edittext.setVisibility(View.VISIBLE);
person_id_edittext.setHint("請輸入查詢personId");
}else {
Person person = personSQLite.find(Integer.parseInt(personId1));
if (person==null){
Toast.makeText(this,"無結果",Toast.LENGTH_SHORT).show();
return;
}
text.setText("personId:"+person.getId()+"\nname:"+person.getName()+"\nphone"+person.getPhone());
person_id_edittext.setText("");
person_id_edittext.setVisibility(View.GONE);
}
break;
case R.id.scroll_date_sql_button:
String num1 = person_num1_edittext.getText().toString();
String num2 = person_num2_edittext.getText().toString();
if (null == num1||"".equals(num1)||null == num2||"".equals(num2)){
person_num1_edittext.setVisibility(View.VISIBLE);
person_num2_edittext.setVisibility(View.VISIBLE);
}else {
List<Person> list = personSQLite.getScrollDate(Integer.parseInt(num1),Integer.parseInt(num2));
if (list==null){
Toast.makeText(this,"無結果",Toast.LENGTH_SHORT).show();
return;
}
for (Person person : list){
text.setText(text.getText().toString()+"\npersonId:"+person.getId()+"\nname:"+person.getName()+"\nphone"+person.getPhone());
}
person_num1_edittext.setText("");
person_num2_edittext.setText("");
person_num1_edittext.setVisibility(View.GONE);
person_num2_edittext.setVisibility(View.GONE);
}
break;
default:
break;
}
}
private void init(){
person_name_edittext = (EditText) findViewById(R.id.person_name_edittext);
person_phone_edittext = (EditText)findViewById(R.id.person_phone_edittext);
person_id_edittext = (EditText) findViewById(R.id.person_id_edittext);
person_num1_edittext = (EditText)findViewById(R.id.person_num1_edittext);
person_num2_edittext = (EditText) findViewById(R.id.person_num2_edittext);
text = (TextView) findViewById(R.id.text);
personSQLite = new PersonSQLite(this);
}
}
XML布局代碼:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
style="@style/MatchMatch"
android:orientation="vertical"
tools:context="com.example.administrator.foundationdemo.sqlite.SQLiteActivity">
<EditText
android:id="@+id/person_name_edittext"
style="@style/MatchWrap"
android:hint="請輸入數(shù)據類容name"/>
<EditText
android:id="@+id/person_phone_edittext"
style="@style/MatchWrap"
android:inputType="number"
android:hint="請輸入數(shù)據類容phone"/>
<EditText
android:id="@+id/person_id_edittext"
style="@style/MatchWrap"
android:inputType="number"
android:visibility="gone" />
<EditText
android:id="@+id/person_num1_edittext"
style="@style/MatchWrap"
android:inputType="number"
android:visibility="gone"
android:hint="請輸入跳過條數(shù)"/>
<EditText
android:id="@+id/person_num2_edittext"
style="@style/MatchWrap"
android:inputType="number"
android:visibility="gone"
android:hint="請輸入查詢條數(shù)"/>
<LinearLayout
android:orientation="horizontal"
style="@style/MatchWrap">
<Button
android:id="@+id/save_sql_button"
style="@style/WrapWrap"
android:onClick="onClick"
android:text="增加數(shù)據"/>
<Button
android:id="@+id/delete_sql_button"
style="@style/WrapWrap"
android:onClick="onClick"
android:text="刪除數(shù)據"/>
<Button
android:id="@+id/update_sql_button"
style="@style/WrapWrap"
android:onClick="onClick"
android:text="修改數(shù)據"/>
<Button
android:id="@+id/find_sql_button"
style="@style/WrapWrap"
android:onClick="onClick"
android:text="查詢數(shù)據"/>
</LinearLayout>
<Button
android:id="@+id/scroll_date_sql_button"
style="@style/WrapWrap"
android:onClick="onClick"
android:text="查詢數(shù)據列表"/>
<TextView
android:id="@+id/text"
style="@style/WrapWrap"/>
</LinearLayout>
效果圖: