插入資料庫某個字段之前判斷是否重複

2021-09-01 15:49:56 字數 918 閱讀 8204

做insert操作時,可能在儲存之前要判斷使用者輸入的某個資料是否在資料庫中唯一存在,是否與其他資料重複。這裡重點記錄sql語句以及service如何實現。

1、錯誤示範

service層:

selmap =commdao.selectone(kfsgl + "kfsdm_q", paramsmap);
dao層:

select 1 as count from dual where exists

select if from fw_sypt_kfsjlb where kfsdm=#

錯誤原因:

1、當使用者輸入的開發商**重複時,sql語句得到的count=1,此時結果與預期相同,使用者無法儲存。

2、當使用者輸入的開發商**不重複時,sql語句得到的count=null,此時沒有返回結果,selectone()查詢出錯,丟擲異常,導致可以儲存的資料無法儲存。原因是:selectone必須返回一條結果。而使用select()查詢時,也會丟擲異常,並且select的返回值是list,不好進行轉換;selectone的返回值型別是map,比較好進行轉換。

2、正確做法

service層:

selmap =commdao.selectone(kfsgl + "kfsdm_q", paramsmap);
dao層:

select count(id) as count from fw_sypt_kfsjlb where kfsdm=#

原理:保證一定有返回值,用到count()函式

判斷sqlite是否包含某個字段

判斷表存在的方法很簡單,網上很多 select count fromsqlite masterwhere type table and name s tname 那麼判斷字段是否存在,或者說如何判斷表的版本是否最新就只需要 select from sqlite master where tbl na...

oracle中判斷某個字段是否存在

oracle中判斷某個字段是否存在 document為表名 docid為欄位名 select count column name from cols where table name upper document and column name upper docid 如果查詢出來的為0說明docu...

Mysql查詢如何判斷字段是否包含某個字串

mysql查詢如何判斷字段是否包含某個字串 有這樣乙個需求,在mysql 資料庫字串字段 許可權 中,使用者有多個不同的郵箱,分別被 分開,現在要取出某個郵箱的所有成員列表。假設有個表 create table users id int 6 not null auto increment,prima...