簡體   English   中英

用戶代碼未處理Sql異常

[英]Sql Exception was unhandled by user code

該網站可以運行,但是當我嘗試登錄該網站時,出現此錯誤:

用戶代碼未處理SQL異常

在這行=>

catch (SqlException e)
{
    throw e;
}

以下是我用於登錄的DBmanager代碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.Data.SqlClient;
using System.Configuration;

namespace TopJobAgencyApp.Class
{
    public class DBManager
    {
        public static int InsertLogin(Registration u)
        {
            int rowsinserted = 0;

            SqlConnection conn = null;

            try
            {
                conn = new SqlConnection();
                conn.ConnectionString = ConfigurationManager.ConnectionStrings["TopJobdb"].ConnectionString;
                conn.Open();

                SqlCommand comm = new SqlCommand();
                comm.Connection = conn;
                comm.CommandText = "INSERT INTO topJobUser(username, email, password)" +
                                   " VALUES (@username, @email, @password)";
                comm.Parameters.AddWithValue("@username", u.UserName);
                comm.Parameters.AddWithValue("@email", u.Email);
                comm.Parameters.AddWithValue("@password", u.Password);

                rowsinserted = comm.ExecuteNonQuery();
            }
            catch (SqlException e)
            {
                throw e;
            }

            return rowsinserted;
        }
    }
}

以下圖片是錯誤消息,請在此處輸入圖像說明

異常非常清楚:

用戶“ user”的登錄失敗。

這意味着與連接字符串關聯的用戶沒有相關SQL Server的登錄權限。

可能的解決方案

  1. 驗證用戶具有SQL Server的登錄權限,然后驗證連接字符串中的憑據。

  2. 如果在IIS下使用Windows身份驗證,則需要將身份驗證模式設置為Windows(請參見下面的示例)。

  3. 如果使用Entity Framework(不是基於示例代碼),則可能需要從連接字符串中刪除Integrated Security=True 並有可能從連接字符串中刪除User Instance=True

Windows身份驗證模式的樣本web.config:

<system.web>
    <authentication mode="Windows"/>
</system.web>

讓我們聊一下發布的代碼...

返回類型

public static int InsertLogin(Registration u)

返回整數的目的是什么? 使用ExecuteNonQuery時,結果是受影響的行總數,其中可能包括受插入觸發器影響的行。 在大多數情況下,insert方法應返回新插入的行的標識或實際插入的新實體。

處置連接

conn = new SqlConnection();

SqlConnection(與SqlCommand一樣)實現IDisposible,因此您希望使用using語句輕松關閉/處置連接。

試着抓

try
{
    // sql
}
catch (SqlException e)
{
    throw e;
}    

沒有任何異常處理的捕捉然后拋出的錢包是什么? 即,日志記錄,重試等。無論如何,如果確實需要重新throw異常,則只需使用throw 通過使用throw e您將丟失堆棧跟蹤。

添加參數

comm.Parameters.AddWithValue("@username", u.UserName);

盡管AddWithValue可以工作,但是最好使用定義的類型添加參數。 請參閱我們可以停止使用AddWithValue()嗎? 欲獲得更多信息。

重構

現在我們有了一些背景,可以清理該方法:

// not ideal, but let's hold the connection string in a backing field
// would be better if the connection string could be passed in at runtime
// instead of the data access layer needing direct access to the config file
private static readonly string ConnString = ConfigurationManager.ConnectionStrings["TopJobdb"].ConnectionString;

public static void InsertLogin(Registration u)
{
    using (var conn = new SqlConnection(ConnString))
    using (var cmd = new SqlCommand()
    {
        cmd.Connection = conn;
        cmd.CommandText = "INSERT INTO topJobUser(username, email, password) VALUES (@username, @email, @password)";

        // be sure to set the size value correctly
        cmd.Parameters.Add("@username", SqlDbType.VarChar, 100).Value = u.UserName;
        cmd.Parameters.Add("@email", SqlDbType.VarChar, 100).Value = u.Email;
        cmd.Parameters.Add("@password", SqlDbType.VarChar, 100).Value = u.password;

        conn.Open();

        cmd.ExecuteNonQuery();
    }
}

筆記:

  • 沒有嘗試/捕獲,因為沒有什么可以恢復的,也沒有其他異常處理得到管理。
  • 該方法返回void,因為返回的行數不向使用者提供任何信息。
  • 如果要返回插入的行的標識,可以搜索幾個示例。

首先,如果要處理異常,則不應“拋出”錯誤。 異常處理的思想是“處理”異常,而不會使您的應用程序崩潰。

您在這里所做的是正在捕獲異常並將其拋出。

您應該修改代碼以顯示友好的錯誤消息,並研究異常消息以及可能存在的其他內部異常。

您創建的異常對象,例如 您將在其屬性中找到許多有用的信息。 您應該瀏覽源代碼,消息,內部異常等。

其次,從您的錯誤消息看來,登錄憑據是錯誤的。 確保您的用戶名和密碼正確。 另外,檢查連接字符串是否正確。

您還可以設置斷點並在執行過程中檢查代碼。

暫無
暫無

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

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