从Java Servlet执行MySQL命令

时间:2012-11-15 21:54:46

标签: java mysql xml jsp servlets

我正在尝试让我的servlet输出用户输入的SQL命令的结果。现在,servlet正确检测命令何时不包含“SELECT”,“INSERT”或“DELETE”,并输出错误消息。当命令有效时,不输出任何内容。我知道这意味着我的问题可能发生在我尝试连接数据库的地方,或者我尝试将输出打印到“out”的地方。

databaseServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;

@SuppressWarnings("serial")
public class databaseServlet extends HttpServlet {
    private Connection conn;
    private Statement statement;

    public void init(ServletConfig config) throws ServletException {
        try {
            Class.forName(config.getInitParameter("databaseDriver"));
            conn = DriverManager.getConnection(
                    config.getInitParameter("databaseName"),
                    config.getInitParameter("username"),
                    config.getInitParameter("password"));
            statement = conn.createStatement();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<xml version = \"1.0\"?>");
        out.println("<!DOCTYPE html PUBLIC \"-//W3C//DTD " +
            "XHTML 1.0 Strict//EN\" \"http://www.w3.org" +
            "/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
        out.println("<html xmlns = \"http://www.w3.org/1999/xhtml\">");
        out.println("<head>");
        out.println("<title>MySQL Servlet</title>");
        out.println("<style type='text/css'>");
        out.println("body{background-color: blue}");
        out.println("</style>");
        out.println("</head>");
        out.println("<body>");

        String query = request.getParameter("query");

        if (query.toLowerCase().contains("select")) {
            //SELECT Queries
            try {
                ResultSet resultSet = statement.executeQuery(query);
                ResultSetMetaData metaData = resultSet.getMetaData();
                int numberOfColumns = metaData.getColumnCount();
                for(int i = 1; i<= numberOfColumns; i++){
                    out.printf("%20s\t", metaData.getColumnName(i));
                }
                out.println();

                while (resultSet.next()){
                    for (int i = 1; i <= numberOfColumns; i++){
                        out.printf("%20s\t", resultSet.getObject(i));
                    }
                    out.println();
                 }
            }
            catch (Exception f) {
                f.printStackTrace();
            }
        }
        else if (query.toLowerCase().contains("delete") || query.toLowerCase().contains("insert")) {
            //DELETE and INSERT commands
            try {
                conn.prepareStatement(query).executeUpdate(query);
                out.println("\t\t Database has been updated!");
            }
            catch (Exception l){
                l.printStackTrace();
            }
        }
        else {
            //Not a valid response
            out.println("\t\t Not a valid command or query!");
        }

        out.println("</body>");
        out.println("</html>");
        out.close();
    }
}

dbServlet.jsp

<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- dbServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
    <title>MySQL Servlet</title>
    <style type="text/css">
        body{background-color: green;}
    </style>
</head>
<body>
    <h1>Hello World!</h1>
    <h2>This is the MySQL Servlet</h2>
    <form action = "/database/database" method = "get">
    <p>
        <label>Enter your query and click the button to invoke a MySQL Servlet
            <input type = "text" name = "query" />
            <input type = "submit" value = "Run MySQL Servlet" />
        </label>
    </p>
    </form>
</body>
</html>

我认为另一个潜在的失败点可能是我的数据库文件路径,该文件在我的web.xml文件中初始化。我在网上找到的一个例子包括端口,但我想知道是否应该删除端口号。有谁知道用于MySQL的默认端口?

这是我在下面的xml文件中讨论的具体行: JDBC:MySQL的://本地主机:3309 / project4

的web.xml

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
  <!-- General description of the web application -->
  <display-name>
    MySQL Servlet
  </display-name>
  <description>
    This web application allows the user to connect to a database, sumbit queries, and make changes.
  </description>
  <!-- Servlet definitions -->
  <servlet>
    <servlet-name>database</servlet-name>
    <description>
        A servlet that handles SQL commands submitted by the user.
    </description>
    <servlet-class>
        databaseServlet
    </servlet-class>
    <init-param>
        <param-name>databaseDriver</param-name>
        <param-value>com.mysql.jdbc.Driver</param-value>
    </init-param>
    <init-param>
        <param-name>databaseName</param-name>
        <param-value>jdbc:mysql://localhost:3309/project4</param-value>
    </init-param>
    <init-param>
        <param-name>username</param-name>
        <param-value>root</param-value>
    </init-param>
    <init-param>
        <param-name>password</param-name>
        <param-value>pass</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>database</servlet-name>
    <url-pattern>/database</url-pattern>
  </servlet-mapping>
</web-app>

1 个答案:

答案 0 :(得分:0)

我使用的是端口3309,需要使用端口3306。

问题

jdbc:mysql://localhost:3309/project4

jdbc:mysql://localhost:3306/project4