写web时用java链接MySQL插入数据服务器报500错误
java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'null' for key 'student.PRIMARY'
java代码
import java.sql.*;
import java.util.Objects;
public class database {
public void insert(String username, String password1, String password2) throws SQLException{
Connection conn= DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root","Hwg2539785237");
try{
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("驱动添加成功,可以进行数据库连接了");
}catch (Exception e){
System.out.println("驱动加载失败,错误原因是:"+e.getMessage());
}
String node="insert into student(id,name,age)values('"+username+"','"+password1+"','"+password2+"')";
//String insert1="insert into student values('hahaha','wotama','jianzhitiancai')";执行注释代码插入常量时可以正确插入
Statement stmt = conn.createStatement();
int result=stmt.executeUpdate(node);
//int result1=stmt.executeUpdate(insert1);
System.out.println(result);
}
}
传给java值的servlet
import java.io.IOException;
import java.sql.SQLException;
import java.util.Objects;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/servlet")
public class servlet extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
String name = request.getParameter("username");
String password1 =request.getParameter("password1");
String password2 =request.getParameter("password2");
database data=new database();
try {
data.insert(name,password1,password2);//调试时这里是有正确参数的
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
报错截图
看到报错里Duplicate entry 'null'感觉是参数没传过来,但是调试的时候显示在database里的username变量是有输入的数据的,不知道是不是语法错误≧ ﹏ ≦
配置:tomcat,MySQL,mysql-connector-java-8.0.28.jar。编译器:idea2023