0

我无法从我的 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。密码和用户名是真实的。

4

2 回答 2

1

MySQL驱动jar文件必须放在你部署的webapp的WEB-INF/lib目录下。

另请注意:

  • JSP 不应访问数据库。这应该在由 servlet 调用的服务中完成。
  • 连接应始终在 finally 块中关闭。如果您有任何异常,不这样做会使连接保持打开状态,并且会很快使系统崩溃
  • webapp 应该使用连接池。阅读您的应用服务器或 Web 容器文档,了解如何设置连接池。
于 2012-12-26T20:16:53.800 回答
0

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

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

于 2012-12-26T19:38:25.807 回答