簡體   English   中英

使用C#在asp.net頁中無法正確執行SqlDataReader

[英]SqlDataReader not executing correctly in asp.net page using C#

我已經使用SqlDataAdapter在代碼的另一部分中訪問了數據庫,但是我只需要一個讀取器即可為我返回一行,並且此代碼無法正常工作。 有人可以看到我在哪里犯錯嗎?

我只是想從返回的行的第一列中為一個標簽分配一個值。 當它在下面運行時,我都不會彈出警報。

private void loadProcInfo(string procid)
{
    try
    {
        SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString);
        SqlCommand query = new SqlCommand("SELECT * FROM dbo.Book1 WHERE ID ='" + procid +"'", con);

        //ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('"+query+"');", true);

        using (SqlDataReader procinfoload = query.ExecuteReader())
        {                    
            if (procinfoload.Read())
            {
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('IT WORKED');", true);
                Id.Text = procinfoload.GetValue(0).ToString();
            }
            else
            {
                ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('not success!');", true);
            }
        }

        con.Close();
    }
    catch (Exception ex)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex + "');", true);
        //MessageBox.Show(ex.Message);
    }
}

嘗試執行閱讀器之前,請先打開連接。

con.Open();

主要問題是在使用命令之前代碼無法打開連接。 但是還有其他問題。

  • 您無需參數化查詢,這會使您的代碼容易受到SQL注入攻擊。
  • 請勿將連接包裝在using塊中,如果引發異常,則連接將保持打開狀態,直到發生垃圾回收為止。 這是不好的做法。

碼:

private void loadProcInfo(string procid)
{
    try
    {
        using(SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString))
        using(SqlCommand query = new SqlCommand("SELECT * FROM dbo.Book1 WHERE ID = @bookId", con))
        {
            // added parameter
            query.Parameters.Add(new SqlParameter("@bookId", SqlDbType.Int){Value = procid});
            con.Open(); // missing
            //ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('"+query+"');", true);
            using (SqlDataReader procinfoload = query.ExecuteReader())
            {                    
                if (procinfoload.Read())
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('IT WORKED');", true);
                    Id.Text = procinfoload.GetValue(0).ToString();
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('not success!');", true);
                }
            }
        }
    }
    catch (Exception ex)
    {
        ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + ex + "');", true);
        //MessageBox.Show(ex.Message);
    }
}

暫無
暫無

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

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