Java 应用程序将空值插入 MySQL 数据库?

mysqlmysqli database更新于 2024/1/9 10:32:00

要使用 Java 设置空值,语句如下 −

ps.setNull(yourIndex, Types.NULL);

首先我们创建一个表 −

mysql> create table DemoTable1893
   (
   FirstName varchar(20)
   );
Query OK, 0 rows affected (0.00 sec)

Java代码如下 −

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Types;
public class InsertNullValueIntoDatabase{
   public static void main(String[] args){
      Connection con=null;
      PreparedStatement ps=null;
      try{
         con=DriverManager.getConnection("jdbc:mysql://localhost:3306/web?useSSL=false",
         "root","123456");
         String query="insert into DemoTable1893(FirstName) values(?) ";
         ps= con.prepareStatement(query);      
         ps.setNull(1, Types.NULL);
         ps.executeUpdate();
         System.out.println("Check the DemoTable1893 ");
      }
      catch(Exception e){
        e.printStackTrace();
      }
   }
}

这将产生以下输出 −

现在使用 select 语句检查 MySQL 表 −

mysql> select * from DemoTable1893;

这将产生以下输出 −

+-----------+
| FirstName |
+-----------+
| NULL      |
+-----------+
1 row in set (0.00 sec)

相关文章