参考链接:http://notfatboy.iteye.com/blog/653357
首先假设有如下表格,表格名称为:"Employees"
SQL基本格式如下:
select 列名称 from 表名称
最基本SQL语句,就是从表中选取要返回的列数据,不加任何过滤条件。当然如果"列名称"是"*",那么将返回整个表格数据。在Android上,SQL相关的method通常有一个参数就是String[] columns,而这个参数对应的就是SQL语句中的"列名称"。可以看一下Android中的method-query:
Cursor query(boolean distinct, String table, String[] columns,
String selection, String[] selectionArgs, String groupBy,
String having, String orderBy, String limit)
各个参数的意义说明:
①table:表名称
②columns:列名称数组
③selection:条件字句,相当于where
④selectionArgs:条件字句,参数数组
⑤groupBy:分组列
⑥having:分组条件
⑦orderBy:排序列
⑧limit:分页查询限制
假设想获取人员的全名,那么SQL语句如下:
select FirstName, LastName from Employees
当然一般地会有条件的过滤,得到自己想要的结果,例如只想返回city为Beijing的人员信息,那么就需要用where来过滤:
select * from Employees where City= 'Beijing'
这里where后面跟的字符串就是Android的method中对应的参数String select。Android的method中通常还有个参数于此相关就是String[] selectionsArgs,当selection参数中包含问号"
?"时,那么selectionArgs才会用到。举个例子,假设selection参数赋值如下:
String selection = "City=?";
这时则必须在selectionArgs参数中赋值为如下:
String[] selectionArgs = {"Beijing"};
也就是说selectionArgs中的字符串就是对应selection中的问号所代表的变量。实际上就是让selection中的过滤添加City可以动态的赋值,而不是写死在程序中。在query()执行时会对selectionArgs中的字符串正确转义并替换到对应的?问号处以构成完整的selection字符串,有点想String.format()。
那么和显然参数String groupBy就是对应SQL语句中的GROUP BY后面的字符串,GROUP BY是与合计函数(Aggregate Functions)如SUM()一起使用的。
参数String having对应SQL语句HAVING后面的字符串,也是要与合计函数一起使用的
参数String orderBy对应SQL语句ORDER BY后面的字符串
参数limit指明返回的rows的数量
下面举个例子,假设有如下数据表,表名"Orders":
假设想查询客户总的订单在300元以上的,且County是city4的客户的名称,且安装CustomeName来排序,默认ASC排序,那么SQL语句应当是:
SELECT CustomerName, SUM (OrderPrice) FROM Orders WHERE Country=?
GROUP BY CustomerName
HAVING SUM (OrderPrice)>300
ORDER BY CustomerName
那么对应Android的query函数的参数如下:
String table = "Orders" ;
String[] columns = new String[] { "CustomerName" , "SUM(OrderPrice)" };
String selection = "Country=?" ;
String[] selectionArgs = new String[]{ "city4" };
String groupBy = "CustomerName" ;
String having = "SUM(OrderPrice)>300" ;
String orderBy = "CustomerName" ;
package com.example.query;
import android.os.Bundle;
import android.util.Log;
import android.app.Activity;
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 MainActivity extends Activity {
private SQLiteDatabase db;
private MyDatabaseUtil databaseUtil;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = this.openOrCreateDatabase("Orders.db", Context.MODE_PRIVATE, null);
databaseUtil = new MyDatabaseUtil(this, "Orders.db", null, 1);
if (!databaseUtil.tabIsExist("Orders")){
db.execSQL("CREATE TABLE Orders (_id integer primary key autoincrement,CustomerName text,OrderPrice INTEGER,Country text,OrderDate data)");
ContentValues contentValues = new ContentValues();
for(int i=0;i<5;i++){
contentValues.put("CustomerName", "name"+ i);
contentValues.put("OrderPrice", 100 + 100*i);
contentValues.put("Country", "city"+ i);
//参数一:表名 参数二:空列的默认值 参数三:ContentValues类型的一个封装了列名称和列值的Map
//一行一行地插入
db.insert("Orders", null, contentValues);
}
}else {
Log.i("+++++++++++", "已经创建了,无需再创建");
}
String table = "Orders" ;
String[] columns = new String[] { "CustomerName" , "SUM(OrderPrice)" };
String selection = "Country=?" ;
String[] selectionArgs = new String[]{ "city4" };
String groupBy = "CustomerName" ;
String having = "SUM(OrderPrice)>300" ;
String orderBy = "CustomerName" ;
Cursor c = db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, null );
c.moveToFirst();
while(!c.isAfterLast()){
int index = c.getColumnIndex("CustomerName");
Log.d("SQLite", c.getString(index));
c.moveToNext();
}
}
public class MyDatabaseUtil extends SQLiteOpenHelper{
public MyDatabaseUtil(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
/**
* 判断某张表是否存在
* @param tabName 表名
* @return
*/
public boolean tabIsExist(String tabName){
boolean result = false;
if(tabName == null){
return false;
}
SQLiteDatabase db = null;
Cursor cursor = null;
try {
db = this.getReadableDatabase();//此this是继承SQLiteOpenHelper类得到的
String sql = "select count(*) as c from sqlite_master where type ='table' and name ='"+tabName.trim()+"' ";
cursor = db.rawQuery(sql, null);
if(cursor.moveToNext()){
int count = cursor.getInt(0);
if(count>0){
result = true;
}
}
} catch (Exception e) {
// TODO: handle exception
}
return result;
}
}
}
打印信息: