Android SQLite数据库中的表详解

Android SQLite数据库

前言

以前写PHP的时候,内置了print_r()和var_dump()两个函数用于打印输出任意类型的数据内部结构,现在做Android的开发,发现并没有这种类似的函数,对于数据库的查看很不方便,于是就写了一下查看数据库表的方法代码。

代码实现

import java.util.Arrays;
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class SecondActivity extends Activity {

  public static final String TAG = "Debug Info";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    ((Button)findViewById(R.id.btnQue)).setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
        MyDatabaseHelper dbhelper = new MyDatabaseHelper(SecondActivity.this, "BookStore.db", null, 1);
        SQLiteDatabase db = dbhelper.getWritableDatabase();

        //核心区
        //读取系统表 sqlite_master
        String sql = "select * from sqlite_master";
        Cursor cursor = db.rawQuery(sql, null);

        //打印表的所有列名
        Log.i(TAG, Arrays.toString(cursor.getColumnNames()));

        //打印当前数据库中的所有表
        if (cursor.moveToFirst()) {
          do {
            String str = "";

            for (String item : cursor.getColumnNames()) {
              str += item + ": " + cursor.getString(cursor.getColumnIndex(item)) + "\n";
            }

            Log.i(TAG, str);

          } while (cursor.moveToNext());
        }
      }
    });
  }

}

功能扩展

查看表是否存在

public Boolean tableIsExist(SQLiteDatabase db, String tableName){
  boolean result = false;
  Cursor cursor = null;

  if(tableName == null){
    return result;
  }

  String sql = "select count(*) from sqlite_master where type ='table' and name ='"+tableName.trim()+"'";
  cursor = db.rawQuery(sql, null);

  if(cursor.moveToNext()){
    if(cursor.getInt(0) > 0){
      result = true;
    }
  }

  return result;
}  

查看数据库中有哪些表

public ArrayList<String> tablesInDB(SQLiteDatabase db){
  ArrayList<String> list = new ArrayList<String>();
  String sql = "select name from sqlite_master where type='table'";
  Cursor cursor = db.rawQuery(sql, null);

  if (cursor.moveToFirst()) {
      do {
        list.add(cursor.getString(0));
      } while (cursor.moveToNext());
    }

  return list;

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!