我正在嘗試在公共類中撰寫一個類似 VBA Access的函式Dcount,以便在我的專案中的任何地方使用它,所以我做了以下操作:Dlookup
public class MyTools
{
SqlConnection Cn = new SqlConnection(@"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True");
SqlDataAdapter da;
DataTable dt = new DataTable();
// DataView dv = new DataView();
SqlCommand cmd;
SqlDataReader DataRead;
// Variables
string MyColumn, MyTable, MyCondition,DlookResult;
int DcountResult;
// Methods & Functions
// Dcount
public int DCount(string MyColumn, string MyTable, string MyCondition)
{
da = new SqlDataAdapter("Select Count(@MyColumn) from @MyTable where @MyColumn = @MyCondition", Cn);
da.Fill(dt);
DcountResult = int.Parse(dt.Rows[0].ToString());
return DcountResult;
}
}
// Dlookup
}
并嘗試像這樣使用它:
int Result = DCount(txtColumn.Text, txtTable.Text, txtCond.Text);
txtResult.Text = null;
txtResult.Text = Result.ToString();
但它拋出錯誤“必須宣告標量變數“@MyColumn”。我嘗試使用sqlcommand,DataRead但我需要在它之后關閉連接return,它在它之前變成Unreachable或關閉,return所以它什么都不回傳,這就是我使用的原因SqlDataAdapter。提前致謝.
uj5u.com熱心網友回復:
它必須看起來更像這樣:
public class MyTools
{
private static string ConnectionString {get;} = @"Server = AMR-PC\SQLEXPRESS ; Database=PlanningDB ; Integrated Security = True";
public static int DCount(string MyTable, string MyColumn, string MyCondition)
{
string sql = $"Select Count({MyColumn}) from {MyTable} where {MyColumn} = @MyCondition";
using (var cn = new SqlConnection(ConnectionString))
using (var cmd = new SqlCommand(sql, cn))
{
cmd.Parameters.AddWithValue("@MyCondition", MyCondition);
cn.Open();
return (int)cmd.ExecuteScalar();
}
}
}
請注意,這使用動態 SQL,而且有點危險。事實上,你不應該這樣做。我知道您不想“繼續輸入 SQL 查詢”,但這可能正是您應該做的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/467140.html
