我寫一個數據庫的servlet連接,一切似乎都很好,只是似乎是一個錯誤在我的連接錯誤在我的數據庫的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"));
}
}
你能告訴我們錯誤是什麼嗎?這段代碼輸出了什麼,你期望它是什麼? – 2010-05-03 20:56:44
如果您將SerialVersionID設置爲簡單地避免警告,請在您的類定義之前將此替代爲@SuppressWarnings(「serial」) – 2010-05-03 23:53:12