【问题标题】:How to assign NULL value to a string and then insert it in mysql database如何将NULL值分配给字符串,然后将其插入mysql数据库
【发布时间】:2017-09-11 11:59:03
【问题描述】:

我在这里计算一列的平均值 如果 avg 为 0.0,那么我想将字符串变量分配为 NULL 否则 avg 值本身。

这些值存储在 mysql db 中 现在我的问题是,当 avg 确实为 0.0 时,字符串 NULL 会被存储,但我希望将默认 NULL 值存储在其中。

如何将 NULL(而不是字符串 NULL)分配给变量 ans??

private void btnAdd1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
     Connection conn = null;
            Statement st = null;          
            ResultSet rs = null;

        try{

  conn = DriverManager.getConnection("jdbc:mysql://localhost/check","root","");
    st = conn.createStatement();

    String sql4 =("SELECT AVG(unit4) as num FROM lo where unit4 IS NOT NULL");
         PreparedStatement pstmt3 = conn.prepareStatement(sql4);
         ResultSet rs4 = pstmt3.executeQuery();
     rs4.next();
     double a3 = rs4.getDouble("num");
     double b3 = Math.round(a3*10);
     double res5 = b3/10;
     rs4.next();
     avg1.setText(String.valueOf(res5));
     String a1 =avg1.getText();
     String ans ;

    if(a1.equals("0.0")){
        ans = null;
    }else{
        ans = a1;
    }

    String query = "INSERT INTO chk(id) VALUES ('"+ans+"')";
    executeSQlQuery(query, "Inserted");

    }   

【问题讨论】:

    标签: java mysql jdbc xampp netbeans-8


    【解决方案1】:

    您可以使用setNull(),为了避免任何语法错误或 SQL 注入,您必须改用 PreparedStatement:

    PreparedStatement ps = connection.prepareStatement("INSERT INTO chk(id) VALUES (?)");
    ps.setNull(1, java.sql.Types.VARCHAR);
    ps.executeUpdate();
    

    注意

    你的程序中有一些东西,为什么你使用rs4.next(); 如果你的结果是空的,我认为你需要这样的东西:

    if (rs4.next()) {//<<<--------------------
        double a3 = rs4.getDouble("num");
        //-----------^^-----------------
    }
    

    【讨论】:

    • 我同意,但这里我首先需要字符串变量中的所有值。我稍后会使用准备好的语句。
    • 那么没有办法将 NULL 分配给变量字符串 ans 吗?
    • @SnehaP 在你的 id 中使用 null 的目的是什么?
    • id int、varchar 或 real 的类型是什么? @SnehaP
    【解决方案2】:

    您没有将ans 括在引号之间来处理NULL 的情况。
    否则,您确实插入 "NULL" String

    String query = "INSERT INTO chk(id) VALUES ('"+ans+"')";
    

    你可以试试:

    String query = "INSERT INTO chk(id) VALUES ("+ ans +")";
    

    【讨论】:

      【解决方案3】:

      您的代码非常不理想,因为您甚至没有使用PreparedStatement。由于您的查询包含'' 标记,因此它将始终在数据库中插入一个字符串。在null 的情况下,您将插入'null',这不是您想要的。

      现在,这不是一个好的解决方案,但它对您来说是最快的。修改查询为"INSERT INTO chk(id) VALUES ("+ans+")",在执行查询前添加如下内容:

      if(ans != null)
          ans = "'" + ans + "'";
      

      记住,这是错误的代码。这不是标准的方式。它有安全问题。学习使用PreparedStatement

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多