将表示 SQL 查询的记录数(计数)的值分配给 C# 中的变量
Posted
技术标签:
【中文标题】将表示 SQL 查询的记录数(计数)的值分配给 C# 中的变量【英文标题】:Assign value that represents the number of records (count) from SQL query to variable in C# 【发布时间】:2021-10-24 12:31:34 【问题描述】:我想在 C# 中创建一个表示查询记录数的变量。 我测试了查询并且工作正常,返回了正确的值。
SELECT Count(c.Cell_ID) AS CountOfCell_ID
FROM Cells AS c
HAVING (((Exists (SELECT 1
FROM ΠΑΡΟΝΤΕΣ as cu
WHERE c.Cell_ID = cu.CellID))=False));
这仅返回一个数字。 我想将该数字(结果)分配给 c# 中的变量。
第一步是在visual studio中编写以下C#代码
int: CountValue;
cnn.ConnectionString = CnnStr;
cnn.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = cnn;
string query = "SELECT Count(c.Cell_ID) AS CountOfCell_ID FROM Cells AS c HAVING(((Exists(SELECT 1 FROM ΠΑΡΟΝΤΕΣ as cu WHERE c.Cell_ID = cu.CellID)) = False));";
接下来我应该怎么做才能将查询中包含的值分配给 CountValue?
【问题讨论】:
docs.microsoft.com/en-us/dotnet/api/… 这么奇怪的写sql的方式.. 这是MS access SQL格式,我只是复制粘贴到post上 HAVING 子句用于聚合函数条件。对常规条件使用 WHERE 子句。 【参考方案1】:接下来你应该执行命令,并读取值:
OleDbCommand command = new OleDbCommand();
command.Connection = cnn;
string query = "SELECT Count(c.Cell_ID) AS CountOfCell_ID FROM Cells AS c HAVING(((Exists(SELECT 1 FROM ΠΑΡΟΝΤΕΣ as cu WHERE c.Cell_ID = cu.CellID)) = False));";
// Open connection
cnn.Open();
// Call command's ExcuteReader
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
// Your value is here
Console.Write("OrderID :" + reader.GetInt32(0).ToString());
// close reader and connection
reader.Close();
cnn.Close();
【讨论】:
我在“OleDbDataReader reader = command.ExecuteReader();”行出现错误 没有为命令对象设置命令文本 我认为 ExecureScalar() 是正确的方法【参考方案2】:以下对我有用
private void DashBoard_Load(object sender, EventArgs e)
// timer1.Start();
string sql = null;
sql = "SELECT Count(c.Cell_ID) AS CountOfCell_ID FROM Cells AS c HAVING(((Exists(SELECT 1 FROM ΠΑΡΟΝΤΕΣ as cu WHERE c.Cell_ID = cu.CellID)) = False));";
try
cnn.ConnectionString = CnnStr;
OleDbCommand command = new OleDbCommand();
command.Connection = cnn;
command= new OleDbCommand(sql, cnn);
cnn.Open();
Int32 count = Convert.ToInt32(command.ExecuteScalar());
command.Dispose();
cnn.Close();
MessageBox.Show(" No of Rows " + count);
cnn.Close();
catch (Exception ex)
MessageBox.Show("Error" + ex);
【讨论】:
以上是关于将表示 SQL 查询的记录数(计数)的值分配给 C# 中的变量的主要内容,如果未能解决你的问题,请参考以下文章