@Test
  public void testTwoConcurrentDbConnections() throws Exception {
    SQLiteDatabase db1 =
        SQLiteDatabase.openDatabase(
            Robolectric.application.getDatabasePath("db1").getPath(), null, 0);
    SQLiteDatabase db2 =
        SQLiteDatabase.openDatabase(
            Robolectric.application.getDatabasePath("db2").getPath(), null, 0);

    db1.execSQL("CREATE TABLE foo(id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT);");
    db2.execSQL("CREATE TABLE bar(id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT);");

    ContentValues d1 = new ContentValues();
    d1.put("data", "d1");

    ContentValues d2 = new ContentValues();
    d2.put("data", "d2");

    db1.insert("foo", null, d1);
    db2.insert("bar", null, d2);

    Cursor c = db1.rawQuery("select * from foo", null);
    assertThat(c).isNotNull();
    assertThat(c.getCount()).isEqualTo(1);
    assertThat(c.moveToNext()).isTrue();
    assertThat(c.getString(c.getColumnIndex("data"))).isEqualTo("d1");

    c = db2.rawQuery("select * from bar", null);
    assertThat(c).isNotNull();
    assertThat(c.getCount()).isEqualTo(1);
    assertThat(c.moveToNext()).isTrue();
    assertThat(c.getString(c.getColumnIndex("data"))).isEqualTo("d2");
  }
예제 #2
0
  /** Open a database connection to an ".anki" SQLite file. */
  @TargetApi(Build.VERSION_CODES.HONEYCOMB)
  public AnkiDb(String ankiFilename) {
    // Since API 11 we can provide a custom error handler which doesn't delete the database on
    // corruption
    if (CompatHelper.isHoneycomb()) {
      mDatabase =
          SQLiteDatabase.openDatabase(
              ankiFilename,
              null,
              (SQLiteDatabase.OPEN_READWRITE + SQLiteDatabase.CREATE_IF_NECESSARY)
                  | SQLiteDatabase.NO_LOCALIZED_COLLATORS,
              new MyDbErrorHandler());
    } else {
      mDatabase =
          SQLiteDatabase.openDatabase(
              ankiFilename,
              null,
              (SQLiteDatabase.OPEN_READWRITE + SQLiteDatabase.CREATE_IF_NECESSARY)
                  | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
    }

    if (mDatabase != null) {
      // TODO: we can remove this eventually once everyone has stopped using old AnkiDroid clients
      // with WAL
      CompatHelper.getCompat().disableDatabaseWriteAheadLogging(mDatabase);
      mDatabase.rawQuery("PRAGMA synchronous = 2", null);
    }
    // getDatabase().beginTransactionNonExclusive();
    mMod = false;
  }
 @Test
 public void testShouldReturnTheSameDatabaseIfAlreadyOpened() throws Exception {
   String path1 = Robolectric.application.getDatabasePath("db1").getPath();
   String path2 = Robolectric.application.getDatabasePath("db2").getPath();
   SQLiteDatabase db1 = SQLiteDatabase.openDatabase(path1, null, 0);
   SQLiteDatabase db2 = SQLiteDatabase.openDatabase(path2, null, 0);
   assertThat(SQLiteDatabase.openDatabase(path1, null, 0)).isSameAs(db1);
   assertThat(SQLiteDatabase.openDatabase(path2, null, 0)).isSameAs(db2);
 }
  private synchronized SQLiteDatabase getReadableDatabase() {
    if (db != null && db.isOpen()) return db;

    db = SQLiteDatabase.openDatabase(DATABASE_FILE, null, SQLiteDatabase.OPEN_READONLY);

    return db;
  }
 // Creating Tables
 @Override
 public void onCreate(SQLiteDatabase db) {
   Log.w("myapp", "dbhandler on create");
   try {
     SQLiteDatabase checkDB = null;
     db = SQLiteDatabase.openDatabase(TABLE_BASKET, null, SQLiteDatabase.OPEN_READWRITE);
     Log.w("myapp", "db exist");
   } catch (SQLiteException e) {
     String CREATE_BASKET_TABLE =
         "CREATE TABLE "
             + TABLE_BASKET
             + "("
             + BASKET_ID
             + " INTEGER PRIMARY KEY AUTOINCREMENT,"
             + ITEM_NAME
             + " TEXT,"
             + ITEM_ID
             + " TEXT,"
             + QTY
             + " INTEGER,"
             + TAXABLE_AMT
             + " Double,"
             + TAX
             + " Double,"
             + TOTAL
             + " Double, "
             + PRICE
             + " Double"
             + ");";
     db.execSQL(CREATE_BASKET_TABLE);
     Log.w("myapp", "db created");
   }
   Log.w("myapp", "dbhandler 1");
 }
예제 #6
0
  public void openDataBase() throws SQLException {

    // Open the database
    String myPath = DB_PATH + DB_NAME;
    myDatabase = this.getReadableDatabase();
    myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
  }
예제 #7
0
  public void createDataBase() throws IOException {
    SQLiteDatabase checkDB = null;
    try {
      String myPath = DB_PATH + DB_NAME;
      checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
    } catch (SQLiteException e) {
    }

    if (checkDB != null) {
      checkDB.close();
    }

    boolean dbExist = checkDB != null ? true : false;
    if (dbExist) {
    } else {
      this.getReadableDatabase();
      try {
        InputStream myInput = myContext.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream myOutput = new FileOutputStream(outFileName);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
          myOutput.write(buffer, 0, length);
        }
        myOutput.flush();
        myOutput.close();
        myInput.close();
      } catch (IOException e) {
        throw new Error("Error copying database");
      }
    }
  }
  private synchronized SQLiteDatabase getDatabase(Context context, boolean retryCopyIfOpenFails) {
    if (mDatabase == null) {
      File dbPath = context.getDatabasePath(DB_NAME);
      try {
        mDatabase =
            SQLiteDatabase.openDatabase(
                dbPath.getAbsolutePath(), null, SQLiteDatabase.OPEN_READONLY);
        if (mDatabase == null) {
          Log.e(TAG, "Cannot open cloud database: " + DB_NAME + ". db == null");
          return null;
        }
        return mDatabase;

      } catch (SQLException ex) {
        Log.e(TAG, "Cannot open cloud database: " + DB_NAME, ex);
        if (mDatabase != null && mDatabase.isOpen()) {
          try {
            mDatabase.close();
          } catch (SQLException ex2) {
            // Ignore
          }
        }

        if (retryCopyIfOpenFails) {
          extractContributorsCloudDatabase(context);
          mDatabase = getDatabase(context, false);
        }
      }

      // We don't have a valid connection
      return null;
    }
    return mDatabase;
  }
 @Test(expected = SQLiteException.class)
 public void testQueryThrowsSQLiteException() throws Exception {
   SQLiteDatabase db1 =
       SQLiteDatabase.openDatabase(
           Robolectric.application.getDatabasePath("db1").getPath(), null, 0);
   db1.query("FOO", null, null, null, null, null, null);
 }
예제 #10
0
 private static void doSomeTrickOnDatabase(String path) throws SQLiteException {
   SQLiteDatabase db = null;
   String myPath = path + File.separator + YGOCardsProvider.DATABASE_NAME;
   db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
   try {
     db.beginTransaction();
     db.execSQL("ALTER TABLE datas RENAME TO datas_backup;");
     db.execSQL(
         "CREATE TABLE datas (_id integer PRIMARY KEY, ot integer, alias integer, setcode integer, type integer,"
             + " atk integer, def integer, level integer, race integer, attribute integer, category integer);");
     db.execSQL(
         "INSERT INTO datas (_id, ot, alias, setcode, type, atk, def, level, race, attribute, category) "
             + "SELECT id, ot, alias, setcode, type, atk, def, level, race, attribute, category FROM datas_backup;");
     db.execSQL("DROP TABLE datas_backup;");
     db.execSQL("ALTER TABLE texts RENAME TO texts_backup;");
     db.execSQL(
         "CREATE TABLE texts (_id integer PRIMARY KEY, name varchar(128), desc varchar(1024),"
             + " str1 varchar(256), str2 varchar(256), str3 varchar(256), str4 varchar(256), str5 varchar(256),"
             + " str6 varchar(256), str7 varchar(256), str8 varchar(256), str9 varchar(256), str10 varchar(256),"
             + " str11 varchar(256), str12 varchar(256), str13 varchar(256), str14 varchar(256), str15 varchar(256), str16 varchar(256));");
     db.execSQL(
         "INSERT INTO texts (_id, name, desc, str1, str2, str3, str4, str5, str6, str7, str8, str9, str10, str11, str12, str13, str14, str15, str16)"
             + " SELECT id, name, desc, str1, str2, str3, str4, str5, str6, str7, str8, str9, str10, str11, str12, str13, str14, str15, str16 FROM texts_backup;");
     db.execSQL("DROP TABLE texts_backup;");
     db.setTransactionSuccessful();
   } finally {
     db.endTransaction();
   }
   if (db != null) {
     db.close();
   }
 }
예제 #11
0
 /**
  * ایجاد یک بانک گنجور خالی
  *
  * @param fileName مسیر فایل
  * @param failIfExists اگر وجود داشته باشد کاری صورت نگیرد
  * @return نتیجۀ عملیات
  */
 public static Boolean CreateNewPoemDatabase(String fileName, Boolean failIfExists) {
   if (failIfExists) {
     File f = new File(fileName);
     if (f.exists()) return false;
   }
   File dbPath = new File(fileName).getParentFile();
   try {
     dbPath.mkdirs();
   } catch (SecurityException e) {
     return false;
   }
   dbPath = new File(fileName);
   if (dbPath.isDirectory()) {
     dbPath.delete();
   }
   SQLiteDatabase newDb;
   try {
     newDb =
         SQLiteDatabase.openDatabase(
             dbPath.getAbsoluteFile().toString(), null, SQLiteDatabase.CREATE_IF_NECESSARY);
   } catch (Exception exp) {
     return false;
   }
   Boolean result = CreateEmptyDB(newDb);
   newDb.close();
   return result;
 }
예제 #12
0
  public ArrayList<String> retrieveNotificationCourses() {
    Cursor res = null;
    SQLiteDatabase db = null;
    ArrayList<String> result = new ArrayList<String>();
    try {
      String query = "SELECT * FROM " + NOTIFICATION_TABLE;
      Log.d("SELECTED", query);
      db =
          SQLiteDatabase.openDatabase(
              DATABASE_PATH + DATABASE_NAME, null, SQLiteDatabase.OPEN_READONLY);

      res = db.rawQuery(query, null);
      while (res.moveToNext()) {
        result.add(res.getString(1));
        // result.add(res.getString(1));
        Log.d("DATABASE QUERY", res.getString(1) + "::\n");
      }
    } catch (Exception e) {
      Log.d("DB", e.getMessage());
    } finally {
      db.close();
      res.close();
    }
    return result;
  }
  public boolean openOrCreateDatabase(Context context, File dbFile) {

    try {

      if (dbFile.exists()) {
        Log.i("SQLiteHelper", "Opening database at " + dbFile);
        mDb =
            SQLiteDatabase.openDatabase(
                dbFile.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
        return true;

        // Test if DB works properly
        // get(MapTile.TABLE_TILE_NAME, "tilekey");
        // ---

        // if (DATABASE_VERSION > db.getVersion())
        // upgrade();
      } else {
        Log.i("SQLiteHelper", "Creating database at " + dbFile);
        mDb = SQLiteDatabase.openOrCreateDatabase(dbFile, null);
        Log.i("SQLiteHelper", "Opened database at " + dbFile);
        upgradeFromFile(mDb, R.raw.sql_osm_maptile);
        return true;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return false;
  }
예제 #14
0
  public boolean deleteNotificationCourses(String number) {
    String query = "";
    SQLiteDatabase db = null;
    try {
      Log.d("NUMBER", number);
      if (number.equals("ALL")) {
        query = "DELETE FROM " + NOTIFICATION_TABLE + ";";
      } else {
        query = "DELETE FROM " + NOTIFICATION_TABLE + " WHERE number like '" + number + "';";
      }
      Log.d("SELECTED", query);
      db =
          SQLiteDatabase.openDatabase(
              DATABASE_PATH + DATABASE_NAME, null, SQLiteDatabase.OPEN_READWRITE);

      db.execSQL(query);
      // db.rawQuery(query, null);
    } catch (Exception e) {
      Log.d("DB", e.getMessage());
      return false;
    } finally {
      db.close();
    }
    return true;
  }
예제 #15
0
  public boolean isTableExtant(String tableName) {

    mDatabase =
        SQLiteDatabase.openDatabase(
            DATABASE_PATH + DATABASE_NAME, null, SQLiteDatabase.OPEN_READONLY);
    boolean openDb = mDatabase.isOpen();

    if (openDb) {
      if (mDatabase == null || !mDatabase.isOpen()) {
        mDatabase = getReadableDatabase();
      }

      if (!mDatabase.isReadOnly()) {
        mDatabase.close();
        mDatabase = getReadableDatabase();
      }
    }

    Cursor cursor =
        mDatabase.rawQuery(
            "select DISTINCT tbl_name from sqlite_master where tbl_name = '" + tableName + "'",
            null);
    if (cursor != null) {
      if (cursor.getCount() > 0) { // table does exist
        cursor.close();
        mDatabase.close();
        return true;
      }
      cursor.close();
    }
    mDatabase.close();
    return false;
  }
예제 #16
0
  public void importContacts() throws Exception {
    String path = mContext.getDatabasePath(DATABASE_NAME).getPath();
    Log.w(TAG, "Importing contacts from " + path);

    if (!new File(path).exists()) {
      Log.i(TAG, "Legacy contacts database does not exist");
      return;
    }

    for (int i = 0; i < MAX_ATTEMPTS; i++) {
      try {
        mSourceDb = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
        importContactsFromLegacyDb();
        Log.i(TAG, "Imported legacy contacts: " + mContactCount);
        mContactsProvider.notifyChange();
        return;

      } catch (SQLiteException e) {
        Log.e(TAG, "Database import exception. Will retry in " + DELAY_BETWEEN_ATTEMPTS + "ms", e);

        // We could get a "database locked" exception here, in which
        // case we should retry
        Thread.sleep(DELAY_BETWEEN_ATTEMPTS);

      } finally {
        if (mSourceDb != null) {
          mSourceDb.close();
        }
      }
    }
  }
  private boolean verificarDB() {
    SQLiteDatabase verDB = null;

    try {

      String miRuta = TodoSQL.dbPath + TodoSQL.nombreDB;
      verDB = SQLiteDatabase.openDatabase(miRuta, null, SQLiteDatabase.OPEN_READWRITE);

    } catch (SQLiteException e) {

      // No existe la base de datos

    }

    if (verDB != null) {

      verDB.close();
      return true;

    } else {

      return false;
    }

    //		return verDB != null ? true : false;

  }
예제 #18
0
  private void openDataBase() throws SQLException {

    // Open the database
    mDataBase =
        SQLiteDatabase.openDatabase(
            context.getFileStreamPath(DB_NAME).toString(), null, SQLiteDatabase.OPEN_READWRITE);
  }
예제 #19
0
 public static SQLiteDatabase OpenDataBase(Context mContext, String dbName, String assertDBName) {
   File dataFolder = mContext.getFilesDir();
   File dbFile = new File(dataFolder.getAbsolutePath() + "/" + dbName);
   Log.v("DataCenter", dbFile.getAbsolutePath());
   if (!dbFile.exists()) {
     try {
       InputStream inputStream = mContext.getAssets().open(assertDBName);
       FileOutputStream fso = new FileOutputStream(dbFile);
       byte[] buffer = new byte[1024];
       int readCount = 0;
       while ((readCount = inputStream.read(buffer)) > 0) {
         fso.write(buffer);
       }
       inputStream.close();
       fso.close();
     } catch (IOException e) {
       // TODO: handle exception
       e.printStackTrace();
     }
   }
   SQLiteDatabase db =
       SQLiteDatabase.openDatabase(
           dbFile.getAbsolutePath(), null, SQLiteDatabase.CREATE_IF_NECESSARY);
   return db;
 }
예제 #20
0
 public DBService() {
   db =
       SQLiteDatabase.openDatabase(
           "/data/data/com.gxu.gxuproject/database/question.db",
           null,
           SQLiteDatabase.OPEN_READWRITE);
 }
  public boolean checkDB() {
    SQLiteDatabase checkDB = null;
    try {
      checkDB = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READWRITE);
    } catch (SQLiteException e) {
      Logging.Log(LOG_TAG, "checkDB() - Database not found");
    }

    if (checkDB != null) {
      if (checkDB.getVersion() != DB_VERSION) {
        Logging.Log(
            LOG_TAG,
            "checkDB() - Wrong DB version: old " + checkDB.getVersion() + " new " + DB_VERSION);
        // checkDB.execSQL("DROP TABLE IF EXISTS " + PREF_TABLE);
        // checkDB.execSQL("DROP TABLE IF EXISTS " + "showsTbl");
        checkDB.close();
        needsUpgrade = true;
        return needsUpgrade;
      } else {
        checkDB.close();
        return true;
      }
    } else {
      return false;
    }
  }
  private DBTileSource(Context context, String path) throws SQLiteException {
    super(null);
    mDB =
        SQLiteDatabase.openDatabase(
            path, null, SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);

    Cursor cursor = mDB.rawQuery("select * from zoom_levels", null);
    try {
      int bbox_x0 = cursor.getColumnIndexOrThrow("bbox_x0");
      int bbox_x1 = cursor.getColumnIndexOrThrow("bbox_x1");
      int bbox_y0 = cursor.getColumnIndexOrThrow("bbox_y0");
      int bbox_y1 = cursor.getColumnIndexOrThrow("bbox_y1");
      int product_code = cursor.getColumnIndexOrThrow("product_code");
      int zoom_level = cursor.getColumnIndexOrThrow("zoom_level");
      ArrayList<ZoomLevel> levels = new ArrayList<ZoomLevel>();
      while (cursor.moveToNext()) {
        ZoomLevel zl =
            new ZoomLevel(
                cursor.getInt(zoom_level),
                cursor.getString(product_code),
                cursor.getInt(bbox_x0),
                cursor.getInt(bbox_x1),
                cursor.getInt(bbox_y0),
                cursor.getInt(bbox_y1));

        levels.add(zl);
      }
      mZoomLevels = levels.toArray(new ZoomLevel[0]);
    } finally {
      cursor.close();
    }
  }
예제 #23
0
  public CartView1(Context context, final Bundle bundle) {
    super(context, bundle);
    goods = new LinkedList<Good>();
    BottomManager.getInstance().showCart();
    database = SQLiteDatabase.openDatabase(GloableParams.PATH, null, SQLiteDatabase.OPEN_READWRITE);
    dao = new GoodDao(context);
    showView = (ViewGroup) View.inflate(context, R.layout.cart, null);
    TitleManager.getInstance().showTwoText();
    TitleManager.getInstance().setLeftButtonText("返回");
    TitleManager.getInstance().setRightButtonText("产看订单");
    TitleManager.getInstance().setTwoText("购物车");
    init();
    // 生成订单
    TitleManager.getInstance()
        .getBtn_name_right()
        .setOnClickListener(
            new OnClickListener() {

              @Override
              public void onClick(View v) {
                // TODO Auto-generated method stub
                // 把购物车id传递到下一个界面
                UIManager.getInstance().changeVew(SelectAddressView.class, bundle);
              }
            });
  }
예제 #24
0
 private SQLiteDatabase openDatabase(Database db) throws SQLiteException {
   Context context = AndroidServiceLocator.getContext();
   return SQLiteDatabase.openDatabase(
       context.getDatabasePath(db.getName()).getAbsolutePath(),
       null,
       SQLiteDatabase.OPEN_READWRITE);
 }
예제 #25
0
 public SQLiteDatabase openDataBase() throws SQLException {
   if (myDataBase == null) {
     String myPath = DATABASE_NAME;
     myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
   }
   return myDataBase;
 }
 public SQLiteDatabase open() {
   if (mDatabase == null || !mDatabase.isOpen()) {
     mDatabase =
         SQLiteDatabase.openDatabase(
             getFile().getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE);
   }
   return mDatabase;
 }
  public void openDataBase() throws SQLException {

    // Open the database
    String myPath = DB_PATH + DB_NAME;
    myDataBase =
        SQLiteDatabase.openDatabase(
            myPath, null, SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
  }
예제 #28
0
    @Override
    protected String doInBackground(Void... url) {
      String response = "";
      SQLiteDatabase checkDB = null;
      Cursor cur = null;
      try {

        String condArt = "";

        if (searchType.equals("C")) {
          if (artType.equals("S")) condArt = " st.id = '" + artName + "' ";
          else condArt = " ar.id like '" + artName + "%' ";
        } else {
          if (artType.equals("S")) condArt = " upper(st.nume) like  upper('" + artName + "%') ";
          else condArt = " upper(ar.nume) like  upper('" + artName + "%') ";
        }

        checkDB =
            SQLiteDatabase.openDatabase(
                ConnectionStrings.getInstance().getNamespace(),
                null,
                SQLiteDatabase.OPEN_READWRITE);
        cur =
            checkDB.rawQuery(
                "SELECT ar.id, ar.nume, st.cod_depart, ar.tip_art FROM articoledef ar, sinteticedef st where "
                    + " st.id = ar.sintetic and "
                    + condArt
                    + " order by ar.nume ",
                null);

        if (cur != null) {
          if (cur.moveToFirst()) {
            do {

              response +=
                  cur.getString(1)
                      + "#"
                      + cur.getString(0)
                      + "#"
                      + cur.getString(2)
                      + "#"
                      + cur.getString(3)
                      + "@@";

            } while (cur.moveToNext());
          }
        }

      } catch (Exception e) {
        errMessage = e.getMessage();
      } finally {

        if (cur != null) cur.close();

        if (checkDB != null) checkDB.close();
      }
      return response;
    }
예제 #29
0
  public void openDataBase() throws SQLException {
    // Open the database

    try {
      myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    } catch (SQLException ex) {
      throw new Error("Error opening database");
    }
  }
  public void InsertToDatabase(String Query) {

    // Used to insert to database
    String myPath = DB_PATH + DB_NAME;
    myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
    myDataBase.execSQL(Query);

    myDataBase.close();
  }