如何从sqlite文件中检索数据

时间:2013-05-21 11:41:22

标签: android sqlite search

我正在进行搜索操作。我创建了一个DBadapter。我只能手动插入值并执行搜索。但我想从sqlite文件中插入数据。如何继续?我应该将该sqlite文件放在assets文件夹中吗?请告诉我如何继续。基本上我想从sqlite文件中搜索数据。

这是我的主要活动代码:

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    searchView = (SearchView) findViewById(R.id.search);
    searchView.setIconifiedByDefault(false);
    searchView.setOnQueryTextListener(this);
    searchView.setOnCloseListener(this);

    mListView = (ListView) findViewById(R.id.list);
    AssetManager manager = this.getAssets();
    mDbHelper = new CustomersDbAdapter(this);
    mDbHelper.open(); 

    mDbHelper.deleteAllCustomers();
    //Add some Customer data as a sample
    mDbHelper.createCustomer("PIZZA1", "Piz", "1107 West Ada", "", "Los Angeles");
    mDbHelper.createCustomer("PIZZA2", "Pizza Hut", "1562 West ", "", "Los Angeles");
    mDbHelper.createCustomer("SUB4", "Subway", "504 West ", "", "Los Angeles");
}

这是DBAdapter:

public class CustomersDbAdapter 
{
    public static final String KEY_ROWID = "rowid";
    public static final String KEY_CUSTOMER = "customer";
    public static final String KEY_NAME = "name";
    public static final String KEY_ADDRESS = "address";
    public static final String KEY_ADDRESS1 = "address1";
    public static final String KEY_ADDRESS2 = "address2";
    public static final String KEY_CITY = "city";
    public static final String KEY_SEARCH = "searchData";

    private static final String TAG = "CustomersDbAdapter";
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    private static final String DATABASE_NAME = "CustomerData";
    private static final String FTS_VIRTUAL_TABLE = "CustomerInfo";
    private static final int DATABASE_VERSION = 1;

    //Create a FTS3 Virtual Table for fast searches
    private static final String DATABASE_CREATE =
    "CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE + " USING fts3(" +
    KEY_CUSTOMER + "," +
    KEY_NAME + "," +
    KEY_ADDRESS1 + "," +
    KEY_ADDRESS2 + "," +
    KEY_CITY + "," +
    //KEY_STATE + "," +
    //KEY_ZIP + "," +
    KEY_SEARCH + "," +
    " UNIQUE (" + KEY_CUSTOMER + "));";


    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.w(TAG, DATABASE_CREATE);
        //db.execSQL(DATABASE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                + newVersion + ", which will destroy all old data");
        db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
        onCreate(db);
    }
}

public CustomersDbAdapter(Context ctx) 
{
    this.mCtx = ctx;
}

public CustomersDbAdapter open() throws SQLException
{
    mDbHelper = new DatabaseHelper(mCtx);
    mDb = mDbHelper.getWritableDatabase();
    return this;
}

public void close() {
    if (mDbHelper != null) {
        mDbHelper.close();
    }
}


public long createCustomer(String customer, String name, String address1, String address2, String city) {

    ContentValues initialValues = new ContentValues();
    String searchValue =     customer + " " + 
                            name + " " + 
                            address1 + " " + 
                            city + " "  
                         //   state + " " + zipCode
                            ;
    initialValues.put(KEY_CUSTOMER, customer);
    initialValues.put(KEY_NAME, name);
    initialValues.put(KEY_ADDRESS1, address1);
    initialValues.put(KEY_ADDRESS2, address2);
    initialValues.put(KEY_CITY, city);
    //initialValues.put(KEY_STATE, state);
    //initialValues.put(KEY_ZIP, zipCode);
    initialValues.put(KEY_SEARCH, searchValue);

    return mDb.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}


public Cursor searchCustomer(String inputText) throws SQLException {
    Log.w(TAG, inputText);
    String query = "SELECT docid as _id," + 
    KEY_CUSTOMER + "," +
    KEY_NAME + "," +
    "(" + KEY_ADDRESS1 + "||" + 
    "(case when " + KEY_ADDRESS2 +  "> '' then '\n' || " + KEY_ADDRESS2 + " else '' end)) as " +  KEY_ADDRESS +"," +
    KEY_ADDRESS1 + "," +
    KEY_ADDRESS2 + "," +
    KEY_CITY + 

    //KEY_ZIP +
    " from " + FTS_VIRTUAL_TABLE +
    " where " +  KEY_SEARCH + " MATCH '" + inputText + "';";
    Log.w(TAG, query);
    Cursor mCursor = mDb.rawQuery(query,null);

    if (mCursor != null) {
        mCursor.moveToFirst();
    }
    return mCursor;

}




}

2 个答案:

答案 0 :(得分:0)

  

我应该将sqlite文件放在assets文件夹中吗?

=>在Android中有两种管理数据库的方法。

  1. 通过代码
  2. 创建新数据库
  3. 使用现有数据库
  4. 通过代码创建新数据库:

    在此方法中,您必须仅通过代码创建数据库和表。我不建议新手程序员使用这种方法,因为SQLite操作代码中可能存在错误。

    这是你的作业:Android database example

    使用现有数据库:

    我建议您使用第二种方法,因为它可以使用一些GUI工具(如SQLite Manager)创建数据库,可以在Mozilla Firefox浏览器中作为工具下载。

    在那里创建一个包含所需表的数据库,并将该数据库文件放在assets文件夹中。

    现在,您必须编写代码才能使用此现有数据库。网上有很多可用的例子。

    这是你的作业:Use existing database in android

答案 1 :(得分:0)

以下是样本:

DBHelper

package vn.mve.db;

import java.util.List;

public interface DBHelper<T> {
    boolean insert(T val);
    boolean update(T val);
    boolean delete(T val);
    List<T> getList(int type);
    T getChild(Object val);
}

DBHandler

public class DBHandler extends SQLiteOpenHelper {
    private static final String TAG = DBHandler.class.getSimpleName();
    protected SQLiteDatabase db; 
    private final Context context;  
    private static String PACKAGE_NAME = "";
    private static int DATABASE_VERSION = 1;

    public DBHandler(Context context) {
        super(context, Def.DBNAME, null, DATABASE_VERSION);
        this.context = context; 
        PACKAGE_NAME = this.context.getPackageName();
        Def.FOLDER_DB = "/data/data/" + PACKAGE_NAME + "/databases/";
        Log.d(TAG, Def.FOLDER_DB);
        try {
            this.createDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }       
    }
    @Override
    public void onCreate(SQLiteDatabase db) {
        try {
            this.createDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        context.deleteDatabase(Def.DBNAME);
        onCreate(db);
    }

    public void createDataBase() throws IOException{
        // for first database;
        boolean dbExist = checkDataBase();
        if(!dbExist){
            try {
                copyDataBase("db/" + Def.DBNAME);
            } catch (Exception e) {
                Log.e(TAG, "createDatabse -> Copy failed!");
                throw new Error("Error copying database");
            }
        } else {
            open();
            boolean isExist = false;
            Cursor cursor = db.rawQuery("select DISTINCT tbl_name from sqlite_master where tbl_name = 'config'", null);
            if (cursor != null) {
                isExist = true;
                cursor.close();
            } else {
                isExist = false;
            }
            close();
            Log.d(TAG, isExist + "");
            if (!isExist) {
                this.context.deleteDatabase(Def.DBNAME);
                try {
                    Log.d(TAG, "createDatabase when database has existed");
                    copyDataBase(Def.DBNAME);
                } catch (Exception e) {
                    Log.e(TAG, "createDatabse -> Copy failed!");
                    throw new Error("Error copying database");
                }               
            }
        }
    }   
    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase(String DB) {
        //Open your local db as the input stream
        InputStream myInput = null;
        //Open the empty db as the output stream
        OutputStream myOutput = null;
        try {
            myInput = context.getResources().getAssets().open(DB);

            // Path to the just created empty db
            String outFileName = Def.FOLDER_DB + Def.DBNAME; 
            myOutput = new FileOutputStream(outFileName);

            //transfer bytes from the inputfile to the outputfile
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0){
                myOutput.write(buffer, 0, length);
            }
        } catch (FileNotFoundException e) {
            Log.e(TAG, "copyDatabase -> File not found.");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e(TAG, "copyDatabase");
        } finally {
              //Close the streams
            try {
                myOutput.flush();
                myOutput.close();
                myInput.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }   
    private boolean checkDataBase(){
        boolean checkDB = false;
        try{
            String myPath = Def.FOLDER_DB + Def.DBNAME;
            File dbFile = new File(myPath); 
            checkDB = dbFile.isFile();
            Log.d(TAG, "checkDatabase: " + String.valueOf(checkDB));
            try {
                File fTmp = new File(Def.FOLDER_DB);
                if (!fTmp.exists()) {
                    fTmp.mkdir();
                }
            } catch (Exception e) {
                Log.e(TAG, "checkDatabase" + e.getMessage());
            }
        }catch(SQLiteException e){}
        return checkDB;
    }
    public void open() {
        try {
            String myPath = Def.FOLDER_DB + Def.DBNAME;
            db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);          
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public synchronized void close() {
            if(db != null)
                db.close();
            super.close();
    }           
    public SQLiteDatabase getSqlDb() {
        return db;
    }
    public void setSqlDb(SQLiteDatabase sqlDb) {
        this.db = sqlDb;
    }    
}

在这里:

public class MVideo extends DBHandler implements DBHelper<Video> {
    public static final String TAG = MVideo.class.getSimpleName();
    public MVideo(Context context) {
        super(context);
    }

    @Override
    public boolean insert(Video val) {
        open();
        ContentValues cValues = new ContentValues();
        cValues.put(Def.Video.ID, val.getId());
        cValues.put(Def.Video.TITLE, val.getTitle());
        cValues.put(Def.Video.THUMBNAIL, val.getThumbnail());
        cValues.put(Def.Video.DESCRIPTION, val.getDescription());
        cValues.put(Def.Video.ENGLISH, val.getEnglish());
        cValues.put(Def.Video.VIETNAMESE, val.getVietnamese());
        cValues.put(Def.Video.ISVIEW, val.getIsView());
        long result = db.insert(Def.Video.NAME, null, cValues);
        close();        
        return result > 0;
    }

    public boolean insertList(List<Video> list) {
        open();
        db.execSQL("BEGIN IMMEDIATE TRANSACTION");
        for (Video v : list) {
            db.execSQL(String.format("INSERT INTO " + Def.Video.NAME + " (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\") VALUES" + 
                    " (\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\",\"%s\")",
                    Def.Video.ID, Def.Video.TITLE, Def.Video.THUMBNAIL, Def.Video.DESCRIPTION, 
                    Def.Video.ENGLISH, Def.Video.VIETNAMESE, Def.Video.ISVIEW,
                    v.getId(), v.getTitle(), v.getThumbnail(), v.getDescription(), v.getEnglish(), v.getVietnamese(), v.getIsView() + ""));
            Log.d(TAG, "insertList -> " + v.toString());
        }
        db.execSQL("COMMIT TRANSACTION");
        close();        
        return true;
    }

    @Override
    public boolean update(Video val) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean delete(Video val) {
        open();
        db.delete(Def.Video.NAME, Def.Video.ID + "=?", new String[]{val.getId()});
        close();
        return false;
    }

    @Override
    public List<Video> getList(int type) {
        List<Video> list = new ArrayList<Video>();
        open();
        Cursor c = db.rawQuery(Def.Video.GET_ALL, null);
        if (c.moveToFirst()) {
            while (c.moveToNext()) {
                String ID = c.getString(0);
                String title = c.getString(1);
                String thumbnail = c.getString(2);
                String description = c.getString(3);
                String english = c.getString(4);
                String vietnamese = c.getString(5);
                boolean isView = Boolean.parseBoolean(c.getString(6));
                list.add(new Video(ID, title, thumbnail, description, english, vietnamese, isView));
            }
        }
        close();
        return list;
    }

    @Override
    public Video getChild(Object val) {
        open();
        Cursor c = db.query(Def.Video.NAME, new String[]{
                Def.Video.ID, Def.Video.TITLE, Def.Video.THUMBNAIL, Def.Video.DESCRIPTION, 
                Def.Video.ENGLISH, Def.Video.VIETNAMESE, Def.Video.ISVIEW
        }, Def.Video.ID + "=?", new String[]{val.toString()}, null, null, null, null);
        if (c != null) {
            c.moveToFirst();
        }
        Video v = new Video(c.getString(0), c.getString(1), 
                c.getString(2), c.getString(3), c.getString(4), 
                c.getString(5), Boolean.parseBoolean(c.getString(6)));
        close();
        return v;
    } 
}

在这里......

List<Video> list = null;
MVideo mVideo = new MVideo(getApplicationContext());
list = mVideo.getList(VideoType.GET_ALL);
VideoAdapter adapter = new VideoAdapter(this, list);
if (list != null) {
    GridView gvVideo = (GridView) findViewById(R.id.gv_video);
    gvVideo.setAdapter(adapter);
}