我有一个带有文本字段的表单。我想让文本字段条目唯一,这样人们就不能再次保存相同的名称。
我们可以使字段在表格列中唯一吗?
或者
我们如何编写一个 JS 代码来使这个字段唯一呢?
这就是我在后端所做的。
public static boolean isUniqueShortName(String sname)
throws DataObjectException
{
return isUniqueShortName(sname, null);
}
public static boolean isUniqueName(String sname, BigDecimal id)
throws DataObjectException
{
final String SELECT_SQL = "SELECT COUNT(*) FROM LISTS WHERE LIST_NAME = ? AND ID <> ?";
final String SELECT_SQL2 = "SELECT COUNT(*) FROM LISTS WHERE LIST_NAME = ?";
boolean exists = false;
Connection conn = DataObjectConnectionPool.getInstance().getConnection();
PreparedStatement pstmt = null;
ResultSet result = null;
try
{
// determine SQL
String SQL = null;
if (list_id != null)
{
SQL = SELECT_SQL;
}
else
{
SQL = SELECT_SQL2;
}
// prepare statement
pstmt = conn.prepareStatement(SQL);
// set parameters
pstmt.setString(1, sname);
if (id != null)
{
pstmt.setBigDecimal(2, id);
}
// execute query
result = pstmt.executeQuery();
// fetch results
while (result != null && result.next())
{
// fetch
int count = result.getInt(1);
exists = (count == 0);
}
// close results
if (result != null)
{
try { result.close(); } catch (Exception e) {}
}
// close statement
if (pstmt != null)
{
try { pstmt.close(); } catch (Exception e) {}
}
}
catch (Exception ex)
{
// throw error
throw new DataObjectException("Error checking for name uniqueness for " + sname);
}
finally
{
// close results
if (result != null)
{
try { result.close(); } catch (Exception e) {}
}
// close statement
if (pstmt != null)
{
try { pstmt.close(); } catch (Exception e) {}
}
// close connection
if (conn != null)
{
try { conn.close(); } catch (Exception e) {}
}
}
return exists;
}