【问题标题】:How to connect to a MongoDB database, in Android?如何在 Android 中连接到 MongoDB 数据库?
【发布时间】:2015-10-08 15:33:01
【问题描述】:

这就是我在项目中添加 Java 驱动程序的方式

compile 'org.mongodb:mongo-java-driver:2.13.2'

在我运行我的 Android 应用 Gradle 之后。 如果我直接添加 jar,我的应用程序无论如何都会崩溃。

连接代码如下:

MongoClient mongoClient = new MongoClient("mongodb://Dbuser:dbpass@ds047692.mongolab.com:47692");
DB db = mongoClient.getDB("testdb");
Set<String> collectionNames = db.getCollectionNames();

我只需要从我的应用程序连接到 mongo 数据库。 我不确定我的连接字符串的正确性。 在我的数据库帐户中,我发现:

通过标准 URI 使用驱动程序进行连接:mongodb://blablauser:password@ds047692.mongolab.com:47692/urdb

但在代码中它没有连接。

我使用 mongo-java-driver。但是每次我尝试阅读我的数据库时,我都会得到

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.artem.mongodb/com.example.artem.mongodb.MainActivity}: com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=ds047692.mongolab.com:47692, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketException: socket failed: EACCES (Permission denied)}, caused by {android.system.ErrnoException: socket failed: EACCES (Permission denied)}}]

Document myDoc = collection.find().first();//crash point

为什么我无法访问自己的数据库?

【问题讨论】:

  • 通过创建 API 层作为“服务”,让您的应用程序连接到数据库层并使用数据。 从不将删除客户端直接连接到数据库。很多安全问题,很多性能优化问题。使用 API。
  • 你打算向公众部署那个应用程序吗?那么这是一个非常非常糟糕的主意。最好在数据库和 Internet 之间放置一个应用程序服务器,以正确执行用户可以和不能对数据库执行的操作。
  • 我只需要通过 url 和 mongo-java-driver 连接到我的数据库
  • 除了之前关于安全问题的 cmets(他们说得对!):您的应用是否有权通过 Internet 连接?

标签: java android mongodb dbconnection


【解决方案1】:

我不知道你是否解决了它,但我遇到了同样的问题,我使用了这个http://docs.mlab.com/data-api/ 使用 http 请求。

【讨论】:

    【解决方案2】:

    试试这个

    MongoClientURI mongoUri  = new MongoClientURI("mongodb://Dbuser:dbpass@ds047692.mongolab.com:47692");
    MongoClient mongoClient = new MongoClient(mongoUri);
    DB db = mongoClient.getDB("testdb");
    Set<String> collectionNames = db.getCollectionNames();
    

    首先你需要将 uri 转换成 MongoClientURI 格式。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-09-24
      • 1970-01-01
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      • 2022-07-18
      • 2023-02-15
      • 2011-07-30
      相关资源
      最近更新 更多