java mysql输入NULL

标签 java mysql insert null

我正在使用 MySQL Server 5.6、Tomcat 8.0。我可以创建一个成功地将硬编码值放入我的表中的 SQL 输入语句,但如果我尝试使用一个变量,它在表中显示为 NULL。我在显示变量正确值的 SQL 语句之前有 println 语句。我的语法看起来正确,正如我所说,它适用于硬编码值。 请原谅代码格式。这应该是一个快速的(哈!)和肮脏的概念证明。

代码片段:

// method to update spice table with input data
  public void update()
  {
    System.out.println("Starting Update");
   java.sql.Date useDate = new java.sql.Date(convert(date));

   Connection conn = null;
   Statement stmt = null;
   String sql;
       try{
    System.out.println("Starting try...");
      // Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      // Open a connection
      System.out.println("Connecting to database...");
      conn = DriverManager.getConnection(DB_URL,USER,PASS);
      System.out.println("Connected database successfully...");

      // Execute update
      System.out.println("Creating statement...");
      stmt = conn.createStatement();
      System.out.println("Name is " + name +".");
      System.out.println("Name is " + getName() +".");
      sql = "INSERT INTO spices VALUES (name, 'location', 'container', 'status', useDate)";
      stmt.executeUpdate(sql);

      // Clean-up environment
      stmt.close();
      conn.close();
   }catch(SQLException se){
      //Handle errors for JDBC
    System.out.println("errors for JDBC");
      se.printStackTrace();
   }catch(Exception e){
      //Handle errors for Class.forName
    System.out.println("errors for Class.forName");
      e.printStackTrace();
   }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException se2){
    System.out.println("SQLException - stmt.close()");
      }// nothing we can do
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){
    System.out.println("SQLException - conn.close()");
         se.printStackTrace();
      }//end finally try
   }//end try
   System.out.println("Goodbye!");
  }

显示 println 输出的服务器日志:

2015-05-25 19:37:46 Commons Daemon procrun stdout initialized
Starting Update
Starting try...
Connecting to database...
Connected database successfully...
Creating statement...
Name is chilli.
Name is chilli.
Goodbye!

表输出:

| NULL      | location  | container | status  | NULL       |

第一个 NULL 应该是“chilli”。 任何帮助将不胜感激 - 我在这里撕头发! 千瓦

最佳答案

应该是

sql = "INSERT INTO spices VALUES ('"+name+"', 'location', 'container', 'status', '"+useDate+"')";

关于java mysql输入NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30444565/

相关文章:

java - 计算包含句子的列表中单词的出现次数

java - 如何使用 Java API Streams 执行此类操作?

java - 如何将jtable中的值插入到mysql中?

java - 类似的接口(interface)

java - 在 playframework 中使用 @Lob 作为字段

MySQL 错误 : Incorrect usage of UPDATE and LIMIT

php - 上传文件

mysql - GROUP_CONCAT - WHERE 条件

php - 错误: Notice: Undefined index

postgresql - 插入后同步两个表