MySQL Connection Error with JSP

2019-06-14 11:15发布

问题:

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();

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...

回答1:

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.

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");
       }

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.



回答2:

In the simplest case, you do:

Class.forName(driverClass);
Connection connection = DriverManager.getConnection(
     "jdbc:mysql://localhost:3306/", userName, password);

If you want to use a container-defined connection pool, and you are using tomcat, take a look at this page

As a sidenote, I don't recommend connecting to a database from a .jsp. Use a servlet for that. JSP is a presentation technology and isn't supposed to have database connectivity logic in it.



标签: java jsp jdbc