【发布时间】:2015-01-28 14:58:41
【问题描述】:
我正在尝试使用 servlet 将 HTML 数据发送到我的数据库中。请帮帮我!
这是我的 doGet 函数
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Student st=new Student();
st.setId(Integer.parseInt(request.getParameter("id")));
st.setName(request.getParameter("name"));
DBConnection db= new DBConnection();
db.addStudent(st);
}
这是我的 addStudent 函数
public class DBConnection {
private static final String driverName = "com.mysql.jdbc.Driver";
static final String URL = "jdbc:mysql://localhost:3306/Test1";
private static final String username = "root";
private static final String password = "root";
public static Connection getConnection() {
System.out.println("HEre");
Connection connection = null;
try {
Class.forName(driverName);
connection = DriverManager.getConnection(URL, username, password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public void addStudent(Student st) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
System.out.println(st.getId() + st.getName());
String Query = "INSERT INTO DETAILS VALUES ( ? , ? , ? )";
connection = getConnection();
preparedStatement = connection.prepareStatement(Query);
preparedStatement.setInt(1, st.getId());
preparedStatement.setString(2, st.getName());
preparedStatement.setBlob(3, (Blob) null);
preparedStatement.executeUpdate();
}
这是我点击提交时遇到的异常:
type Exception report
message description The server encountered an internal error that prevented it from fulfilling this request.
exception java.lang.NullPointerException
DataAccessObject.DBConnection.addStudent(DBConnection.java:42)
ActionObject.Input.doGet(Input.java:36)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
这些是我的 apache 服务器日志:
127.0.0.1 - - [28/Jan/2015:19:13:02 +0530] "GET /Test1/Input?name=&id=&mydropdown=Coding&mydropdown=Coding&marks=&submitbtn=Submit HTTP/1.1" 500 1478
127.0.0.1 - - [28/Jan/2015:20:09:15 +0530] "GET / HTTP/1.1" 200 11243
【问题讨论】:
-
DBConnection的第 42 行是哪一行?我猜Connection对象没有被正确初始化。您必须调试您的应用程序。 -
@NikosParaskevopoulos 我已经编辑了我的帖子以显示更多代码。这是行:
preparedStatement = connection.prepareStatement(Query); -
所以.. 连接为空。查看 getConnection() 函数中的
-
你能做一个调试运行,看看你到底在哪里得到错误?谢谢(你确定数据库的密码是“root”吗?)
-
通常你必须在项目的“WEB-INF”文件夹中创建一个“lib”文件夹,并将 mysql-connector-java 放在“lib”文件夹中......然后添加外部jar 到项目的 java 构建路径
标签: java html apache servlets connection