链接到mongoDB java驱动程序时出错

时间:2014-01-02 12:29:43

标签: java mongodb mongo-java

我从这里下载了mongo-java-driver-2.11.2.jar文件 - http://central.maven.org/maven2/org/mongodb/mongo-java-driver/2.11.3/ 在我的示例应用程序中,我有以下代码 -

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;
MongoClient mongoclient = new MongoClient("localhost",27017);

DB db = mongoclient.getDB("test1");

我总是得到这个错误 -

[parsing started RegularFileObject[myfile.java]]
myfile.java:11: class, interface, or enum expected
MongoClient mongoclient = new MongoClient("localhost",27017);
^
myfile.java:12: class, interface, or enum expected
DB db = mongoclient.getDB("test1");▒
^
[parsing completed 26ms]
[total 54ms]
2 errors 

我尝试了各种编译选项:

javac myfile.java 

因为.jar在同一目录中。

javac -cp '.:mongo-java-driver-2.11.2.jar' myfile.java

甚至是文件的完整路径

javac -classpath '/home/nimish/HTMLProjects/mongodbJavaIntro/mongo-java-driver-2.11.2-sources.jar' myfile.java -verbose

但无济于事。任何人都可以对此有所了解。

1 个答案:

答案 0 :(得分:1)

你缺少一个班级名称:

public class myfile { ...

缺乏一些基本的编程习惯。应该为您的班级MyFile命名

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 myfile {

    DB db; 

    public myfile {
        initDB();
    }

    public void initDB() {
        MongoClient mongoclient = new MongoClient("localhost",27017);
        db = mongoclient.getDB("test1");
    }

    ...


}