如何进行数据库查询并在表中显示结果?

时间:2016-07-14 16:20:45

标签: android database

我是数据库的新手,在查看有关导入SQLite数据库的其他问题之后选择此实现,如何查询搜索“select ... from ...”并在表中显示结果? (机器人)

    TestAdapter mDbHelper = new TestAdapter(getContext());
    mDbHelper.createDatabase();
    mDbHelper.open();
    Cursor testdata = mDbHelper.getTestData();
    mDbHelper.close();

更新1 试过这个来测试内容:

    TestAdapter mDbHelper = new TestAdapter(getContext());
    mDbHelper.createDatabase();
    mDbHelper.open();
    Cursor testdata = mDbHelper.getTestData();
    int number = testdata.getCount();
    TextView myTextView = (TextView) getView().findViewById(R.id.textView14);
    myTextView.setText("My int value is " + number);
    mDbHelper.close();

获取此错误

 android.database.sqlite.SQLiteException: Can't downgrade database from version 10 to 1
                                                           at android.database.sqlite.SQLiteOpenHelper.onDowngrade(SQLiteOpenHelper.java:360)
                                                           at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:254)

我的DatabaseHelper clas:

public class DataBaseHelper extends SQLiteOpenHelper
{
     private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
//destination path (location) of our database on device
private static String DB_PATH = "";
private static String DB_NAME ="ACR_DB";// Database name
private SQLiteDatabase mDataBase;
private final Context mContext;

public DataBaseHelper(Context context)
{
    super(context, DB_NAME, null, 1);// 1? Its database Version
    if(android.os.Build.VERSION.SDK_INT >= 17){
        DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
    }
    else
    {
        DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
    }
    this.mContext = context;
}

public void createDataBase() throws IOException
{
    //If the database does not exist, copy it from the assets.

    boolean mDataBaseExist = checkDataBase();
    if(!mDataBaseExist)
    {
        this.getReadableDatabase();
        this.close();
        try
        {
            //Copy the database from assests
            copyDataBase();
            Log.e(TAG, "createDatabase database created");
        }
        catch (IOException mIOException)
        {
            throw new Error("ErrorCopyingDataBase");
        }
    }
}

//Check that the database exists here: /data/data/your package/databases/Da Name
private boolean checkDataBase()
{
    File dbFile = new File(DB_PATH + DB_NAME);
    //Log.v("dbFile", dbFile + "   "+ dbFile.exists());
    return dbFile.exists();
}

//Copy the database from assets
private void copyDataBase() throws IOException
{
    InputStream mInput = mContext.getAssets().open(DB_NAME);
    String outFileName = DB_PATH + DB_NAME;
    OutputStream mOutput = new FileOutputStream(outFileName);
    byte[] mBuffer = new byte[1024];
    int mLength;
    while ((mLength = mInput.read(mBuffer))>0)
    {
        mOutput.write(mBuffer, 0, mLength);
    }
    mOutput.flush();
    mOutput.close();
    mInput.close();
}

//Open the database, so we can query it
public boolean openDataBase() throws SQLException
{
    String mPath = DB_PATH + DB_NAME;
    //Log.v("mPath", mPath);
    mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
    //mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
    return mDataBase != null;
}

@Override
public synchronized void close()
{
    if(mDataBase != null)
        mDataBase.close();
    super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}

}

我的testAdapter

   public class TestAdapter
 {
protected static final String TAG = "DataAdapter";

private final Context mContext;
private SQLiteDatabase mDb;
private DataBaseHelper mDbHelper;

public TestAdapter(Context context)
{
    this.mContext = context;
    mDbHelper = new DataBaseHelper(mContext);
}

public TestAdapter createDatabase() throws SQLException
{
    try
    {
        mDbHelper.createDataBase();
    }
    catch (IOException mIOException)
    {
        Log.e(TAG, mIOException.toString() + "  UnableToCreateDatabase");
        throw new Error("UnableToCreateDatabase");
    }
    return this;
}

public TestAdapter open() throws SQLException
{
    try
    {
        mDbHelper.openDataBase();
        mDbHelper.close();
        mDb = mDbHelper.getReadableDatabase();
    }
    catch (SQLException mSQLException)
    {
        Log.e(TAG, "open >>"+ mSQLException.toString());
        throw mSQLException;
    }
    return this;
}

public void close()
{
    mDbHelper.close();
}

public Cursor getTestData()
{
    try
    {
        String sql ="SELECT * FROM myTable";

        Cursor mCur = mDb.rawQuery(sql, null);
        if (mCur!=null)
        {
            mCur.moveToNext();
        }
        return mCur;
    }
    catch (SQLException mSQLException)
    {
        Log.e(TAG, "getTestData >>"+ mSQLException.toString());
        throw mSQLException;
    }
}

}

2 个答案:

答案 0 :(得分:0)

我在另一个应用程序中使用这样的东西。在您的活动中编写一个创建表行的方法。

public Tablelayout table;

    public void populateTable(String queryResult){
          table = (TableLayout)findviewbyid(R.id.<yourtablename>);
          TableRow tr = new TableRow(this);
          tr.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
          TextView myDbResult = new TextView(this);
          myDbResult.setText(queryResult);
          tr.addView(myDbResult);
          table.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.MATCH_PARENT));
    }

在您的DatabaseHelper中执行此操作。

private SQLiteDatabase db;
public YourActivity yourActivity;

    public DatabaseHelper(Context c){
        myContext = c;
        yourActivity = (YourActivity) myContext;

    }

    public void getData(){
        Cursor c = db.rawQuery("SELECT * FROM YourTable", null);
        c.moveToFirst();
        while (c.isAfterLast() == false){
            String myQueryResult = cursor.getString(cursor.getColumnIndex("ColumnName"));
            yourActivity.PopulateArtist(myQueryResult);
            cursor.moveToNext();
        }

    return c;
}

这应该通过数据库表,并且对于每个条目在主活动中创建一行,其中包含数据。

答案 1 :(得分:0)

您的错误日志表明您的数据库版本是10,但您已将其设置为1。你可以从最后super(context, DB_NAME, null, 1);// 1? Its database Version的这个1设置为10。