赞
踩
Java 数据库连接 (JDBC) API 允许 Java 程序员访问不同的关系和 NoSQL 数据库,如 Oracle、MySQL、SQL Server 等。它有助于存储、访问和操作存储在这些数据库中的数据。
在这篇文章中,我们将探讨如何在 PreparedStatement 中设置 NULL 值。
- String name = null;
- Long id = null;
-
- PreparedStatement ps = connection.prepareStatement("select * from person where first_name = ? and id = ?");
-
- ps.setString(1,name);
ps.setLong(2, id);
- if( id == null ) {
- ps.setNull(2, Types.INTEGER);
- }else {
- ps.setLong(2, id);
- }
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Types; public class JDBCNullExample { public static void main(String[] args) throws Exception{ Connection connection = null; try { connection = openConnection(); String name = null; Long id = null; PreparedStatement ps = connection.prepareStatement("select * from person where first_name = ? and id = ?"); ps.setString(1,name); if(id == null) { ps.setNull(2, Types.INTEGER); }else { ps.setLong(2, id); } ResultSet rs = ps.executeQuery(); System.out.println(rs.getFetchSize()); rs.close(); }catch(Exception exception) { exception.printStackTrace(); }finally { if(connection != null) { connection.close(); } } } private static Connection openConnection() throws Exception{ Class.forName("oracle.jdbc.OracleDriver"); return DriverManager.getConnection("jdbc:oracle:thin:@IP:orcl", "user","password"); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。