java连接MongoDB的方法(包括java和MongoDB环境的搭建)

首先在官网官网:http://www.mongodb.org/下载最新的mongodb。

在硬盘中新建一个名为mongodb的文件夹,我的位置是 d:\mongodb。在该文件夹中新建名为data和logs的文件夹,分别存放数据库数据和日志。

将下载好的文件解压,复制bin文件夹中的所有文件到之前新建的文件夹mongodb中。在cmd中分别输入命令:

D:

cd mongodb

mongod.exe --dbpath=d:/mongodb/data --logpath=d:/mongodb/logs/mongodb.log –install

到这里mongo数据库就安装成功,并且加入windows的服务项,在控制面板----管理工具----服务中将mongodb设为自启动项,在浏览器中输入localhost:27017可以看到以下内容:

You are trying to access MongoDB on the native driverport. For http diagnostic access, add 1000 to the port number

到此mongo数据库安装成功。

在浏览器中输入http://localhost:28017/可以监视mongodb的运行状态。

 

 

到SUN官网下载JDK最新开发包,一般运行后将SDK和JRE一起安装。安装后配置环境变量如表所示。

环境变量配置

变量名

变量值

JAVA_HOME

C:\Program Files\Java\jdk1.6.0_26 (安装路径)

path

%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin

classpath

.;%JAVA_HOME%\lib\tools.jar;%JAVA_HOME%\lib\dt.jar;

配置好后测试一下,测试程序如下:

importjava.util.*;

importjava.awt.*;

importjava.awt.event.*;

 

publicclass helloworld{

       public static void main(String[] args){

              System.out.println("HelloWorld!");

              System.out.println(new Date());

              }

       }

将程序另存为helloworld.java,注意文件名要与类名一样,不然编译时会出现错误。

在windows控制台也就是cmd中,跳转到helloworld.java的文件目录下,输入javac helloworld.java执行编译,编译完成后,可能在控制台中不会出现什么反应,输入java helloworld,将会出现以下信息:

HelloWorld!

ThuFeb 02 16:55:50 CST 2012

到此为止,java环境搭建完毕。

 

 

在尝试用java连接mongodb之前,我们下载mongodb的java驱动,下载地址:https://github.com/mongodb/mongo-java-driver/downloads

注意下载对应的版本,我的mongodbdb是2.0.2,所以下载mongo-2.0.jar — Version 2.0

在Eclipse官网上下载java版的Eclipse,就是第一个,网址:http://www.eclipse.org/downloads/

下载完成后,Eclipse新建一个java project,我新建一个名为MongoDB的工程,新建好了后,右键单-->build path-->add external archives-->找到之前下载好的驱动包添加。
Mongodb的基本操作:
进入cmd控制台,按照之前的方法进入MongoDB目录,输入mongo.exe,再输入
use testdb创建testdb数据库
输入db.addUser(“test”, “123”)为testdb创建一个用户,下面是连接数据库的测试代码:

import com.mongodb.DB;//加载MongoDB的java驱动

import com.mongodb.Mongo;

 

public class connection {

    public static void main(String[] args) throws Exception {

        Mongo m = new Mongo("localhost", 27017);

        DB db = m.getDB("test ");

        if(db.authenticate("test", "123".toCharArray())){

            System.out.println("success");;

        }

        else System.out.println("false");

    }

}    

 

注意文件名和类名要相同。

发布了29 篇原创文章 · 获赞 0 · 访问量 9万+
展开阅读全文

java项目连接mongoDB报错

08-14

在本地搭了环境,启动mongoDB数据库服务并进行了连接验证,如下: ![图片说明](https://img-ask.csdn.net/upload/201708/14/1502695838_396993.png) ![图片说明](https://img-ask.csdn.net/upload/201708/14/1502695905_168178.png) 启动eclipse,登录页面时会访问mongoDB,但总是连接超时,报错信息如下: org.springframework.dao.DataAccessResourceFailureException: 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=172.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}]; nested exception is 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=172.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}] at org.springframework.data.mongodb.core.MongoExceptionTranslator.translateExceptionIfPossible(MongoExceptionTranslator.java:73) at org.springframework.data.mongodb.core.MongoTemplate.potentiallyConvertRuntimeException(MongoTemplate.java:2002) at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1885) at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1696) at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1679) at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:598) at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:589) at com.jftt.wifi.service.impl.ManageUserServiceImpl.findUserByCondition(ManageUserServiceImpl.java:301) at com.jftt.wifi.service.impl.ManageUserServiceImpl.findUserByCondition(ManageUserServiceImpl.java:273) at com.jftt.wifi.service.impl.ManageUserServiceImpl.findUserByUserName(ManageUserServiceImpl.java:664) at com.jftt.wifi.action.LoginAction.login(LoginAction.java:369) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863) at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318) at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.lang.Thread.run(Unknown Source) Caused by: 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=172.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket}, caused by {java.net.SocketTimeoutException: connect timed out}}] at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:370) at com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:101) at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:75) at com.mongodb.binding.ClusterBinding$ClusterBindingConnectionSource.<init>(ClusterBinding.java:71) at com.mongodb.binding.ClusterBinding.getReadConnectionSource(ClusterBinding.java:63) at com.mongodb.operation.OperationHelper.withConnection(OperationHelper.java:166) at com.mongodb.operation.FindOperation.execute(FindOperation.java:394) at com.mongodb.operation.FindOperation.execute(FindOperation.java:57) at com.mongodb.Mongo.execute(Mongo.java:738) at com.mongodb.Mongo$2.execute(Mongo.java:725) at com.mongodb.DBCursor.initializeCursor(DBCursor.java:815) at com.mongodb.DBCursor.hasNext(DBCursor.java:149) at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1871) ... 49 more 请问各位大侠,有碰到这样的问题么?如何解决呢? 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览