什么我无法从我的jsp连接到mysql?

时间:2012-12-26 18:28:48

标签: java

我无法从我的jsp连接到数据库。代码如下

  <% 
        try {
        /* Create string of connection url within specified format with machine name, 
        port number and database name. Here machine name id localhost and 
        database name is usermaster. */ 
        String connectionURL = "jdbc:mysql://localhost:3306/test"; 

        // declare a connection by using Connection interface 
        Connection connection = null; 

        // Load JBBC driver "com.mysql.jdbc.Driver" 
        Class.forName("com.mysql.jdbc.Driver").newInstance(); 

        /* Create a connection by using getConnection() method that takes parameters of 
        string type connection url, user name and password to connect to database. */ 
        connection = DriverManager.getConnection(connectionURL, "root", "pass");

        // check weather connection is established or not by isClosed() method 
        if(!connection.isClosed())
        %>
        <font size="+3" color="green"></b>
        <% 
        out.println("Successfully connected to " + "MySQL server using TCP/IP...");
        connection.close();
        }
        catch(Exception ex){
        %>
        </font>
        <font size="+3" color="red"></b>
        <%
        out.println("Unable to connect to database.");
        }
        %>

我连接到数据库和事件搜索查询可能是什么问题?我只是从一个来源c / p并把我的jsp。密码和用户名为真。

2 个答案:

答案 0 :(得分:1)

MySQL驱动程序jar文件必须放在已部署的webapp的WEB-INF / lib目录中。

另请注意:

  • JSP不应该访问数据库。这应该在servlet调用的服务中完成。
  • 应始终在finally块中关闭连接。如果你有任何例外,不这样做会使连接保持打开状态,并且会很快使系统陷入困境
  • webapp应该使用连接池。阅读您的应用服务器或Web容器文档,了解如何设置连接池。

答案 1 :(得分:0)

将异常消息添加到自己创建的错误输出中:

out.println(“无法连接数据库:”+ ex.getMessage());