[英]How to check for not null fields before inserting record into a database table Java
我只需要通過插入主鍵字段值來在數據庫表(MySQL,Oracle,MSSQL)中創建/插入新記錄。 但是,如果表中有一列不允許空值,則此方法不起作用。 如何檢查不允許空值的表列。
您可以例如在啟動時針對表執行請求,然后檢查表的元數據:
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");
}
簽出DatabaseMetadata對象,尤其是getAttributes()方法。
NULLABLE int =>是否允許NULL
attributeNoNulls - might not allow NULL values attributeNullable - definitely allows NULL values attributeNullableUnknown - nullability unknown
我確實認為(但是)您的應用程序應該盡可能多地知道。 數據約束。 數據庫受到這些約束的保護,但是應用程序應該(如果可能)知道並尊重此信息。
看起來應該這樣: 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
像這樣測試每個表:
步驟1:嘗試將具有空值的記錄插入表中。
步驟2:如果出現異常,請捕獲該異常,然后對其他表進行這些步驟。
您可以標記這些表或具有包含表名的列表。
您也可以檢查ResultSetMetaData。 Java文檔
ResultSetMetaData.columnNullable
ResultSetMetaData.columnNoNulls
ResultSetMetaData.columnNullableUnknown
問候
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.