Error with connection in my database servlet
- by Zerobu
Hello, I am writing a Database servlet, all seems well except that there seems to be an error in my connection
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" ) );
}
}