Home >Database >Mysql Tutorial >How to Insert NULL Values into a Constrained Integer Column using JDBC?

How to Insert NULL Values into a Constrained Integer Column using JDBC?

Linda Hamilton
Linda HamiltonOriginal
2024-12-29 00:54:09168browse

How to Insert NULL Values into a Constrained Integer Column using JDBC?

Inserting Null to an Integer Column using JDBC

Suppose you have a SQL column named PROTOCOL that is nullable and has the following constraint:

PROTOCOL IN (1, 2, 3)

You want to insert and retrieve null values into this column using JDBC.

The standard methods setInt() and getInt() cannot handle null values directly. Instead, you can use the setNull() method to explicitly set a column to null.

Syntax:

pst.setNull(columnIndex, sqlType)
  • pst is an instance of the PreparedStatement class.
  • columnIndex is the index of the column you want to set to null.
  • sqlType is the SQL type of the column. For integer columns, this would be java.sql.Types.INTEGER.

Example:

// Get the prepared statement instance
PreparedStatement pst = connection.prepareStatement("INSERT INTO table_name (PROTOCOL) VALUES (?)");

// Set the PROTOCOL column to null
pst.setNull(4, java.sql.Types.INTEGER);

// Execute the statement
pst.executeUpdate();

By using setNull(), you can set null values into integer columns even if they have constraints.

The above is the detailed content of How to Insert NULL Values into a Constrained Integer Column using JDBC?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn