MongoDB java驱动程序给出错误`令牌上的语法错误,删除这些令牌`

时间:2013-10-06 02:46:38

标签: java mongodb

这是我第一次尝试使用MongoDB java驱动程序,所以我只是尝试了这些示例。我已经将驱动程序jar添加到库中,并且所有导入都可以正常工作。但是,每当我尝试写任何其他内容时,例如MongoClient mongoClient = new MongoClient();,我都会收到错误Syntax error on tokens, delete these tokens。事实上,它不仅仅是特定于mongo。写任何东西都会产生这个错误。

如果答案非常明显,我道歉:/

1 个答案:

答案 0 :(得分:0)

尝试将语句放在类中,如下所示:

    import com.mongodb.MongoClient;
    import com.mongodb.MongoException;
    import com.mongodb.WriteConcern;
    import com.mongodb.DB;
    import com.mongodb.DBCollection;
    import com.mongodb.BasicDBObject;
    import com.mongodb.DBObject;
    import com.mongodb.DBCursor;
    import com.mongodb.ServerAddress;

    import java.util.Arrays;

    public Class MongoSample{

    // To directly connect to a single MongoDB server (note that this will not auto-discover the primary even
    // if it's a member of a replica set:
    MongoClient mongoClient = new MongoClient();
    // or
    MongoClient mongoClient = new MongoClient( "localhost" );
    // or
    MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
    // or, to connect to a replica set, with auto-discovery of the primary, supply a seed list of members
    MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("localhost", 27017),
                                          new ServerAddress("localhost", 27018),
                                          new ServerAddress("localhost", 27019)));

    DB db = mongoClient.getDB( "mydb" );
}

请在发布之前尝试调查google / stackoverflow上的问题。你会学到很多东西,并且能够帮助别人。

我从这个answer

中得到了可能的问题的提示