2012-12-26 34 views
0

我无法从我的jsp连接到数据库。代码如下什么我不能从我的jsp连接到mysql?

<% 
     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。密码和用户名是真实的。

+0

它抛出的异常是什么? – Smit

+0

它只是打印'无法连接到数据库。' – abc

+0

异常是java.lang.ClassNotFoundException:com.mysql.jdbc.Driver – abc

回答

0

添加例外消息给你自己创建的错误输出:

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

1

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

还要注意的是:

  • 的JSP不应该访问数据库。这应该在servlet调用的服务中完成。
  • 连接总是应该在finally块中关闭。如果您有任何异常,不这样做会使连接断开,并且会很快使系统瘫痪
  • webapp应该使用连接池。阅读您的应用程序服务器或Web容器文档以了解如何设置连接池。
相关问题