使用jsp抛出异常插入mysql数据库

问题描述 投票:0回答:2

我正在尝试将信息从注册表单页面存储到相应的数据库,但代码正在抛出异常,因为“无法连接到数据库”我是一个初学者,并且很难在这里弄清楚出了什么问题。有人可以帮忙吗?

<%@page import="java.sql.*"%>
<html>
<head>  
<meta charset="utf-8">  
<title>Sign Up</title> 
<link rel="stylesheet" type="text/css" href="reg.css">
</head>  
<body> 

<%
  String name = request.getParameter("name");
  String email = request.getParameter("email");
  String password = request.getParameter("password");
  String date = request.getParameter("date");
  String sex = request.getParameter("sex");

  Connection con = null;
  PreparedStatement ps = null;

  String connectionURL = "jdbc:mysql://localhost:3306/table";
  String driverName = "com.mysql.jdbc.Driver";
  String user = "root";
  String pass = "";

  Class.forName(driverName).newInstance();

       try {

            con = DriverManager.getConnection(connectionURL, user, pass);

          String queryString = "INSERT INTO detail(name,password,email,date,sex) VALUES (?,?,?,?,?)";

          ps = con.prepareStatement(queryString);
                ps.setString(1, name);
          ps.setString(2, password);
        ps.setString(3, email);
        ps.setString(4, date);
          ps.setString(5, sex);

          int updateQuery = ps.executeUpdate();
                        if (updateQuery != 0) { 
                            out.println("Successful Registration");
                         }
        } 
        catch (Exception ex) {
        out.println("Unable to connect to database.");

           }
        finally {
            // close all the connections.
            ps.close();
            con.close();
         }
 %>

</body>
</html>
mysql database jsp jdbc
2个回答
0
投票
  1. 您是否在项目中包含了驱动程序jar文件?
  2. String connectionURL = "jdbc:mysql://localhost:3306/table";,table是您想要连接的数据库名称吗?
  3. catch (Exception ex) { out.println("Unable to connect to database."); }

包括ex.printStackTrace(),它会告诉您确切的错误。


0
投票

嗯......“无法连接到数据库”就是这个意思。您的JSP无法连接到数据库。

请在您的问题中添加完整的堆栈跟踪(错误)。这样就会更清楚问题是什么。

在我的头顶,可能的罪魁祸首是:

  1. 您没有在JEE容器中加载驱动程序。你添加了数据库驱动程序吗?
  2. 您的驱动程序配置不正确。添加驱动程序时是否指定了正确的“驱动程序类”?
  3. 你的网址错了。请检查URL的值。它结构良好吗?按照确切的格式作为示例,并插入您的特定值。
  4. 实际上没有数据库在主机上运行:PORT。数据库是否已创建?
  5. 您的凭据错误,已禁用或尚未存在。使用DBA检查您的用户名和密码。你有合适的吗?

因此,如果您已经检查过并且您认为所有这些都是好的,请首先使用独立客户端检查连接。这样你就可以看到是否可以建立连接。我推荐使用Squirrel SQL Client或Eclipse的Data Source Explorer。试试看你有没有合适的参数。

检查与本地客户端的连接后,所有内容都应在JEE容器中运行。

© www.soinside.com 2019 - 2024. All rights reserved.