连接数据库servlet时出错

时间:2010-05-03 20:21:30

标签: java servlets jdbc

我正在编写一个数据库servlet,一切似乎都很好,除了我的连接中似乎有错误

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DBServlet3 extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    @Override
    public void init() throws ServletException
    {
        super.init();
        try
        {
            String jdbcDriverClass= 
                getServletContext().getInitParameter( "jdbcDriverClass" );
            if (jdbcDriverClass == null)
                throw new ServletException( "Could not find jdbcDriverClass initialization parameter" );
            Class.forName( jdbcDriverClass );
        }
        catch (ClassNotFoundException e)
        {
            throw new ServletException( "Could not load JDBC driver class", e );
        }
    }

    @Override
    protected void doGet( HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException
    {
        RequestDispatcher dispatcher=
            request.getRequestDispatcher( "/db.jsp" );

        ServletContext application= getServletContext();

        ArrayList<String> names= new ArrayList<String>();

        try
        {

            Connection connection= null;
            Statement statement= null;
            ResultSet results= null;

            try
            {
                String jdbcUrl= application.getInitParameter( "jdbcUrl" );
                String jdbcUser= application.getInitParameter( "jdbcUser" );
                String jdbcPassword= application.getInitParameter( "jdbcPassword" );

                connection=
                    DriverManager.getConnection( jdbcUrl, jdbcUser, jdbcPassword );

                statement= connection.createStatement();

                results= statement.executeQuery( "SELECT * FROM students" );

                while (results.next())
                {
                    String name= results.getString( "name" );
                    names.add( name );
                }
            }
            finally
            {
                if (results != null)
                    results.close();
                if (statement != null)
                    statement.close();
                if (connection != null)
                    connection.close();
            }
        }
        catch (SQLException e)
        {
            throw new ServletException( e );
        }

        request.setAttribute( "names", names );

        dispatcher.forward( request, response );
    }

    @Override
    protected void doPost( HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException
    {
        String sql= "INSERT INTO students VALUES (" +
            request.getParameter( "id" ) + ", '" + request.getParameter( "name" ) + "')";

        sql= "INSERT INTO students VALUES (?, ?, ?, ?)";

        PreparedStatement statement= connection.prepareStatement( sql ); //error on this line

        statement.setString( 1, request.getParameter( "id" ) );
        statement.setString( 2, request.getParameter( "name" ) );
    }

}

1 个答案:

答案 0 :(得分:2)

我一点也不清楚具体问题是什么,我会编辑添加一个堆栈跟踪。但是,有些观察。

  1. 您正在使用doGet()方法获取和关闭连接,但您的doPost()方法中没有连接。这样会导致错误。您应该按照请求以一致的方式获取连接,并且可能(进一步)检查连接池框架,例如C3P0Apache DBCP
  2. 而不是从构建字符串形成SQL,请查看PreparedStatements。它们将导致更少出错的代码并保护您免受SQL注入攻击。
  3. 您的servlet中有serialVersionUid。你真的需要序列化你的servlet(我怀疑不是)?
  4. Apache DbUtils会为你做很多繁重的工作。 vanilla JDBC(例如,它将查看结果集/语句/连接关闭序列)。