簡體   English   中英

如何在數據庫中的字段不允許空值時處理異常

[英]how to handle exception when a field in database does not allow nulls

我在數據庫中有一個nvarchar的字段,它不能為null。 發生錯誤時顯示特定消息時出現問題。 在我的數據庫中插入時,我嘗試了兩件事。 第一:

if (string.IsNullOrWhiteSpace(textBoxCity.Text))
    MessageBox.Show("This cannot be empty");
else  
    cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = textBoxCity.Text;

第二:

try
{
    if(string.IsNullOrWhiteSpace(textBoxCity.Text))
    {
        MessageBox.Show("Cannot be empty");

    }
    else
    {
        cmd.Parameters.Add("@city", SqlDbType.NVarChar).Value = textBoxCity.Text;
    }
}
catch (Exception ex)
{
    if (ex is FormatException)
    {
        MessageBox.Show("Cannot be empty");
        return;
    }
    else if (ex is SqlException)
    {
        MessageBox.Show("Cannot be empty");
    }
    throw;
}

第二個給了我正確的信息,但它也給了我一個例外,它說必須聲明標量。我能處理嗎? 我試圖給它一個db.null,但因為一個字段不允許空值,它給了我另一個異常,再次不是格式,或sql.Can你告訴我這是什么樣的異常,或者如何我可以處理嗎?

編輯:起初我有一個錯誤,它應該是nvarchar sqldbtype,有int。

cmd.Parameters.Add("@city", SqlDbType.Int).Value = textBoxCity.Text;

您將參數定義為int類型,並為其提供string 您需要將TextBox中的值解析為int。

int city = 0;
int.TryParse(textBoxCity.Text, out city)
cmd.Parameters.Add("@city", SqlDbType.Int).Value = city;

如果該值是必需的但未提供,則不應嘗試將其插入到數據庫中 - 當然這會導致異常。

bool valid = true;
if (string.IsNullOrWhiteSpace(textBoxCity.Text))
{
     valid = false;
     MessageBox.Show("This cannot be empty");
}

if(valid)
{
    cmd.Parameters.Add("@city", SqlDbType.Int).Value = textBoxCity.Text;
    //execute sql query here
}

正如另一個答案所說,你也應該將文本解析成一個int。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM