Eclipse jsp报错500 jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null

javax.servlet.ServletException: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'id' cannot be null

这样报错

jsp代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>插入学生信息</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
String id = request.getParameter("id");
String name = request.getParameter("name");
String age = request.getParameter("age");
String gender = request.getParameter("gender");
String major = request.getParameter("major");
Connection conn = null;
Statement stat = null;

Class.forName("org.gjt.mm.mysql.Driver");
String url = "jdbc:mysql://localhost:3306/Test";
String user = "root";
String password = "";
conn = DriverManager.getConnection(url, user, password);
stat = conn.createStatement();
String sql = "insert into student(id,name,age,gender,major)values("
+ id + ",'" + name + "'," + age + ",'" + gender + "','"
+ major + "')";
int i = stat.executeUpdate(sql);
%>

<center>
<%
if (i != 0) {
out.print("<br><h3>成功输入!</h3>");
} else {
out.print("<br><h3>输入失败!</h3>");
}
%>

<br> <a href=submit.jsp>返回信息输入页面</a> <a href=layout.jsp>进入信息查询页面</a>
</center>
<%
if (stat != null) {
stat.close();
}
if (conn != null) {
conn.close();
}
%>
</body>
</html>

当你插入数据的时候 id获取到的是可能是null
你打个断点 跟踪下,看看是不是null追问

我把数据库改了一下改成这样就好了 我也不知道为什么要这样才行 是查到的  但是把auto_increment删掉就不行 但是老师给的数据库是没有这样的 我完全不着边际不懂什么意思  不过不管了  谢谢了

追答

这是个非空字段,你需要给这个字段赋值
你原来没有赋值,但是又非空,所以报错了

现在你让它自增长了 ,那么你就不用赋值了
都满足数据库主键不为空且唯一的标准,所以就不报错了
当然,如果你代码中有手动赋值的话,只要是唯一的值 ,也不会报错, 你可以试试

温馨提示:答案为网友推荐,仅供参考
相似回答