[英]re-using code and variables in asp.net webapp (c# beginner)
Ive在VS2012中創建了一個webapp。 該應用程序的目的是更新整個公司范圍內不同顯示器上顯示的數據。 每個顯示都有自己的數據要顯示。 所有數據都存儲在單個SQL表中,並具有特定的列以了解必須在什么顯示上顯示哪些數據。 該webapp由不同的aspx頁面組成,以更新不同屏幕上的數據,因此我具有UpdateScreen1.aspx,UpdateScreen2.aspx等。這些頁面的核心大約有90%相同。 它們從SQL連接開始,獲取此特定屏幕的數據列表(因此,除了WHERE子句外,SQL語句是相同的),當然還有數據的創建/更新/刪除功能。 例如,如果需要更改我的select語句,則必須更新所有頁面。 另外,在每個頁面中分別指定了SQL連接。 我想知道是否可以通過重用例如select語句(定義一次,並僅在特定頁面中添加where子句),sql連接來使它性能更高,但是我可以做到這一點。似乎找不到放置它們的位置。 我已經嘗試過一個單獨的類文件global.asax,但是似乎沒有任何作用(名稱xxxxx在當前上下文中不存在...)。
這里是我的一些代碼:UpdateScreen1.aspx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
namespace RSS_Aankondigingen.UpdateScreen1
{
public partial class Update_Announcement : System.Web.UI.Page
{
private SqlConnection sqlConn = new SqlConnection("Data Source=server;Initial Catalog=db;Persist Security Info=True;User ID=user;Password=password");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvBind();
}
}
protected void gvBind()
{
sqlConn.Open();
string a = sqlSelect;
SqlCommand sqlCmd = new SqlCommand("SELECT ID, Title, CONCAT(CONVERT(char(16), Date, 103),CONVERT(char(5), Date, 108)) AS Date, Recurrent FROM tblAnnouncements WHERE Channel = 'SH_ANN' ORDER BY Date", sqlConn);
SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCmd);
DataSet ds = new DataSet();
sqlDA.Fill(ds);
sqlConn.Close();
if (ds.Tables[0].Rows.Count > 0)
{
GridAnnouncements.DataSource = ds;
GridAnnouncements.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
GridAnnouncements.DataSource = ds;
GridAnnouncements.DataBind();
int colCount = GridAnnouncements.Rows[0].Cells.Count;
GridAnnouncements.Rows[0].Cells.Clear();
GridAnnouncements.Rows[0].Cells.Add(new TableCell());
GridAnnouncements.Rows[0].Cells[0].ColumnSpan = colCount;
GridAnnouncements.Rows[0].Cells[0].Text = "Geen gegevens gevonden...";
}
}
}
}
任何幫助將不勝感激。
米歇爾。
編輯:未注釋的sqlConn初始化(用於測試)
如果使用的是ADO,則可以將存儲過程與參數一起使用,然后SqlCommand成為存儲過程的名稱(將CommandType更改為StoredProcedure),然后將參數添加到命令中。
但是,還應研究諸如Entity Framework之類的更現代的選項,您將對一些Announcement對象使用Linq。
回答您的問題,創建另一個類,然后使用它包裝sql代碼。 (這全部來自內存,因此,如果有錯誤,我們深表歉意。)
即
namespace RSS_Aankondigingen
public class DatbaseHelper
{
public DataSet GetDataSet(string selectOn)
{
sqlConn.Open();
string sqlQuery = string.format("SELECT ID, Title, CONCAT(CONVERT(char(16), Date, 103),CONVERT(char(5), Date, 108)) AS Date, Recurrent FROM tblAnnouncements WHERE Channel = '{0}' ORDER BY Date", selectOn);
SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCmd);
DataSet ds = new DataSet();
sqlDA.Fill(ds);
sqlConn.Close();
return ds;
}
}
然后在您的代碼中,當您需要進行選擇時;
替換上面的所有代碼。 (其中SH_ANN是您希望在該頁面上選擇的內容。)
DataSet ds = GetDataSet("SH_ANN");
這不是最佳解決方案,但第一步,它將使您可以將SQL代碼隔離到單個類中,從而使維護更加容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.