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
Release: 2024-12-29 00:54:09
Original
189 people have browsed it

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)
Copy after login

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)
Copy after login
  • 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();
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template