JSP的MySQL连接错误 [英] MySQL Connection Error with JSP

查看:77
本文介绍了JSP的MySQL连接错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从jsp页面连接到mysql数据库.这 连接代码如下

I am trying to connect to mysql database from jsp page. The connection code is as below

   InitialContext ic=new InitialContext();
   DataSource ds=(DataSource)ic.lookup("jdbc:mysql://localhost:3306/");
   Connection con=ds.getConnection();
    Statement stmt = con.createStatement();

当我打开页面时,出现以下错误 javax.servlet.ServletException:javax.naming.NamingException:查找 在SerialContext [Root]中因"jdbc:mysql://localhost:3306/"而失败 异常是javax.naming.NameNotFoundException:jdbc:mysql:]

when i open the page i get the following error javax.servlet.ServletException: javax.naming.NamingException: Lookup failed for 'jdbc:mysql://localhost:3306/' in SerialContext [Root exception is javax.naming.NameNotFoundException: jdbc:mysql:]

有人可以告诉我这是怎么回事...

can some one please tell me what is wrong with this...

推荐答案

您正尝试使用JNDI查找持久连接. JNDI用于在servlet容器中存储和访问资源,但是您使用的是JDBC连接字符串而不是JNDI引用.

You're trying to look up a persistent connection using JNDI. JNDI is used to store and access resources in a servlet container, but you're using a JDBC connection string instead of a JNDI reference.

如果要通过页面中的JDBC直接连接到数据库,则需要类似以下内容的连接.

If you want to connect direct to your database via JDBC in the page, you want something like the following to get your connection.

       Connection conn = null;

       try {
           String userName = "myuser";
           String password = "mypassword";
           String url = "jdbc:mysql://localhost:3306/mydb";
           Class.forName ("com.mysql.jdbc.Driver").newInstance ();
           conn = DriverManager.getConnection (url, userName, password);
       } catch (Exception e) {
           System.err.println ("Cannot connect to database server");
       }

另一方面,如果您想使用JNDI,则需要先将连接存储在JNDI中,然后通过用于存储连接的名称在JSP中访问它.这是一个更复杂的过程,因此,这是一个链接到在Tomcat文档中的适当位置,其中说明了操作方法.

If, on the other hand you want to use JNDI, you need to store the connection in JNDI first, then access it in your JSP via the name you used to store it. It's a more complex process, so here's a link to the appropriate place in the Tomcat documentation that explains how to do it.

这篇关于JSP的MySQL连接错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆