|
i'm beginner of jsp and servlet and i want to connect to mysql i have one servlet to do this in the init method etablish my connection but when run it this error is been null pointer refrence of this statement
Statement statement = connection.createStatement();
here the code of servlet
package EngyTest01;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import util.*;
/**
*
* @author ENG_ELMALA7
* @version
*/
public class Sql extends HttpServlet {
private Connection connection ;
public void init() throws ServletException{
try{
Class.forName("org.gjt.mm.mysql.Driver");
String dbURL = "jdbc:mysql://localhost/engydb";
// String dbURL = "jdbc:mysql:engydb";
String username = "root";
String password = "";
connection = DriverManager.getConnection(
dbURL, username, password);
}
catch(ClassNotFoundException e){
System.out.println("Database driver not found.");
}
catch(SQLException e){
System.out.println("Error opening the db connection: "
+ e.getMessage());
}
}
public void destroy() {
try{
connection.close();
}
catch(SQLException e){
System.out.println("Error closing the db connection: "
+ e.getMessage());
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
String sqlStatement = request.getParameter("sqlStatement");
String message = "";
try{
Statement statement = connection.createStatement();
sqlStatement = sqlStatement.trim();
String sqlType = sqlStatement.substring(0, 6);
if (sqlType.equalsIgnoreCase("select")){
ResultSet resultSet = statement.executeQuery(sqlStatement);
// create a string that contains a HTML-formatted result set
message = SQLUtil.getHtmlRows(resultSet);
}
else
{
int i = statement.executeUpdate(sqlStatement);
if (i == 0) // this is a DDL statement
message = "The statement executed successfully.";
else // this is an INSERT, UPDATE, or DELETE statement
message = "The statement executed successfully.<br>"
+ i + " row(s) affected.";
}
statement.close();
}
catch(SQLException e){
message = "Error executing the SQL statement: <br>"
+ e.getMessage();
}
HttpSession session = request.getSession();
session.setAttribute("message", message);
session.setAttribute("sqlStatement", sqlStatement);
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(
"/forum/SQL_GATEWAY.html");
dispatcher.forward(request, response);
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
doGet(request, response);
}
}
|
|
|
|
|
|
|
|