简体   繁体   English

如何在将记录插入数据库表Java中之前检查非空字段

[英]How to check for not null fields before inserting record into a database table Java

I have to create / insert a new record in a database table (MySQL, Oracle, MSSQL) only by inserting the primary key field values. 我只需要通过插入主键字段值来在数据库表(MySQL,Oracle,MSSQL)中创建/插入新记录。 But this is not working if there is a column in the table which does not allow null values. 但是,如果表中有一列不允许空值,则此方法不起作用。 How can I check the table columns which do not allow null values. 如何检查不允许空值的表列。

You can execute a request against your table, for example at startup time, and then check the metadata of your table: 您可以例如在启动时针对表执行请求,然后检查表的元数据:

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM myTable");
ResultSetMetaData rsmd = rs.getMetaData();
int nullable = rsmd.isNullable(1);
if(nullable == ResultSetMetadata.columnNullable) {
    System.out.println("Nullable");
}

Check out the DatabaseMetadata object and in particular the getAttributes() method. 签出DatabaseMetadata对象,尤其是getAttributes()方法。

NULLABLE int => whether NULL is allowed NULLABLE int =>是否允许NULL

 attributeNoNulls - might not allow NULL values attributeNullable - definitely allows NULL values attributeNullableUnknown - nullability unknown 

I do think (however) that your application should know as much as possible re. 我确实认为(但是)您的应用程序应该尽可能多地知道。 the data constraints. 数据约束。 The database protects itself with these constraints, but the application should (where possible) know and respect this info. 数据库受到这些约束的保护,但是应用程序应该(如果可能)知道并尊重此信息。

It looks like this should work: ResultSetMetaData.isNullable 看起来应该这样: ResultSetMetaData.isNullable

public int isNullable(int column)
           throws SQLException

Indicates the nullability of values in the designated column.

Parameters:
    column - the first column is 1, the second is 2, ... 
Returns:
    the nullability status of the given column; one of columnNoNulls, columnNullableor columnNullableUnknown 
Throws:
    SQLException - if a database access error occurs

If I get you right, you are looking for a way to test the tables in your program (and I assume not manually)... 如果我说对了,您正在寻找一种方法来测试程序中的表(我认为不是手动进行的)...
Test each table like this: 像这样测试每个表:
Step 1: Try inserting a record with null values to your table. 步骤1:尝试将具有空值的记录插入表中。
Step 2: If exception rises, catch it and proceed these steps with other tables. 步骤2:如果出现异常,请捕获该异常,然后对其他表进行这些步骤。

You can mark those tables or have a list which contains tables' names for you. 您可以标记这些表或具有包含表名的列表。

You could check ResultSetMetaData as well. 您也可以检查ResultSetMetaData。 javadoc Java文档

ResultSetMetaData.columnNullable
ResultSetMetaData.columnNoNulls
ResultSetMetaData.columnNullableUnknown

Regards 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM