[英]How to do size validation of values for columns before inserting data into table in sql for DB2?
I need to check whether the value is with proper size to be inserted into a table for particular column before actual insertion of data into table. 在将数据实际插入表之前,我需要检查该值是否具有正确的大小以插入到特定列的表中。
eg, 例如,
Suppose, I have a table 'MyTable' with column 'MYSMALLINT' of SMALLINT type in DB2, 假设我在DB2中有一个表“ MyTable”,表中的列“ MYSMALLINT”为SMALLINT类型,
If I try to insert the value as, 如果我尝试将值插入为,
insert into MyTable(MYSMALLINT) values(12222222222222222222222222222225552);
I will get below error, after executing the above query: 执行以上查询后,我将得到以下错误:
Message: The numeric literal "12222222222222222222222222222225552" is not valid because its value is out of range. 消息:数字文字“ 12222222222222222222222222222225552”无效,因为其值超出范围。
Here, I need to check the size of value before inserting the data into table in Java/JDBC for a column with any data type(CHAR,VARCHAR,INT,BIGINT,TINYINT,DOUBLE,FLOAT,DECIMAL,REAL,...). 在这里,我需要在将数据插入Java / JDBC中的表中的任何数据类型(CHAR,VARCHAR,INT,BIGINT,TINYINT,DOUBLE,FLOAT,DECIMAL,REAL等)的数据之前检查值的大小。 。
You can do it with PreparedStatement
: 您可以使用PreparedStatement
做到这一点:
PreparedStatement statement = connection.prepareStatement("insert into MyTable(MYSMALLINT) values(?);"
for(Integer value:values){
try{
statement.setInt(1,value);
statement.addBatch();
}catch(SQLException e){
System.err.println("Invalid value: " + e.getMessage());
throw e;
}
}
statement.executeBatch();
You can validate the before value in a trigger if it is valid for your requirements. 如果满足您的要求,则可以在触发器中验证之前的值。 The way you validate the value can a UDF, in that way you can test it outside the trigger. 验证值的方式可以是UDF,那样您就可以在触发器外部对其进行测试。
Why not just map the column to the correct Java primitive. 为什么不将列映射到正确的Java原语。
Smallint is equivalent to a "short" in Java so if you defined your host variable as a short the compiler would detect any errors at compile time. Smallint等效于Java中的“ short”,因此,如果将主机变量定义为short,则编译器将在编译时检测到任何错误。
insert into MyTable(MYSMALLINT) values(12222222222222222222222222222225552S);
would be spat out by your java compiler. 将被您的Java编译器吐出来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.