【问题标题】:My webapp still insert " " and null values how can I fix this?我的 webapp 仍然插入“”和空值我该如何解决这个问题?
【发布时间】:2016-02-06 12:02:21
【问题描述】:

我有一个包含问题和答案的 Mysql 表

        CREATE TABLE question(
        id INT PRIMARY KEY NOT NULL AUTO_INCREMENT,
        ttype INT NOT NULL,
        content VARCHAR(1000) NOT NULL,
        a1 VARCHAR(200) NOT NULL,
        a2 VARCHAR(200) NOT NULL,
        a3 VARCHAR(200) NOT NULL,
        a4 VARCHAR(200) NOT NULL,
        a5 VARCHAR(200) NOT NULL,
       correctAnswer VARCHAR(10)
       )

我正在使用(MVC JSP servlet)插入数据库

我在 DAO 类中的 addquestion() 是

 public int Addquestion(Question q){
 int type = q.getTtype();
 String content = q.getContent();
 String a1 = q.getA1();
 String a2 = q.getA2();
 String a3 = q.getA3();
 String a4 = q.getA4();
 String a5 = q.getA5();
 String correctAnswer =q.getCorrectAnswer();

 Connection con = null;
 PreparedStatement insertQuestion = null;
 int result = 0;
 try{
     con = DBConnection.createConnection();
     insertQuestion = con.prepareStatement("insert into question(ttype,content,a1,a2,a3,a4,a5,correctAnswer) VALUES (?,?,?,?,?,?,?,?)");
     insertQuestion.setInt(1,type);
     insertQuestion.setString(2,content);
     insertQuestion.setString(3, a1);
     insertQuestion.setString(4, a2);
     insertQuestion.setString(5, a3);
     insertQuestion.setString(6, a4);
     insertQuestion.setString(7, a5);
     insertQuestion.setString(8, correctAnswer );

     result = insertQuestion.executeUpdate();


 }
 catch(SQLException e){
     e.printStackTrace();
 }


  return result;
  }

问题是我认为 (NOT NULL) 足以在 (web App) 提交空表单时返回错误 (result=0)。但我的数据库仍然采用空值(或“”)?

(注意:我不确定当我提交 null 或 "" 时 HTML 空表单返回什么)

非常感谢

【问题讨论】:

    标签: mysql jsp servlets model-view-controller


    【解决方案1】:

    是的,它肯定会在数据库中添加null or "" 值。为什么因为prepared statement会创建类似这样的SQL(如果你想看到最终的查询,把System.out.println(insertQuestion);放在executeUpdate()之前)

    insert into question(ttype,content,a1,a2,a3,a4,a5,correctAnswer) VALUES (1,'test','test','test','test','test','test','test')
    

    现在假设您没有在 HTML 表单中为某些 not null 字段添加任何值,而不是查询将变为

    (1,'test','test','test','test','','','test') 
    

    并且empty String ("") 不等于null,即使您将null 放在HTML 形式中,尽管它会将其视为

    (1,'test','test','test','test','null','null','test') 
    

    它将插入数据库(无错误)。

    因此最好将验证放在客户端(Javascript,jQuery)上,而不是在服务器上验证它。

    希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 2020-03-25
      • 2020-02-14
      • 1970-01-01
      • 2021-07-31
      • 2020-12-28
      • 2019-12-03
      相关资源
      最近更新 更多