【发布时间】:2013-11-23 09:57:35
【问题描述】:
如何计算c#中sql表的行数? 我需要从我的数据库中提取一些数据...
【问题讨论】:
如何计算c#中sql表的行数? 我需要从我的数据库中提取一些数据...
【问题讨论】:
你可以这样尝试:
select count(*) from tablename where columname = 'values'
C# 代码将是这样的:-
public int A()
{
string stmt = "SELECT COUNT(*) FROM dbo.tablename";
int count = 0;
using(SqlConnection thisConnection = new SqlConnection("Data Source=DATASOURCE"))
{
using(SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
}
}
return count;
}
【讨论】:
您需要先从 c# 建立数据库连接。然后,您需要将以下查询作为 commandText 传递。
Select count(*) from TableName
使用 ExecuteScalar/ExecuteReader 获取返回的计数。
【讨论】:
你的意思是喜欢这个吗?
SELECT COUNT(*)
FROM yourTable
WHERE ....
【讨论】:
你可以制作一个你可以一直使用的全局函数
public static int GetTableCount(string tablename, string connStr = null)
{
string stmt = string.Format("SELECT COUNT(*) FROM {0}", tablename);
if (String.IsNullOrEmpty(connStr))
connStr = ConnectionString;
int count = 0;
try
{
using (SqlConnection thisConnection = new SqlConnection(connStr))
{
using (SqlCommand cmdCount = new SqlCommand(stmt, thisConnection))
{
thisConnection.Open();
count = (int)cmdCount.ExecuteScalar();
}
}
return count;
}
catch (Exception ex)
{
VDBLogger.LogError(ex);
return 0;
}
}
【讨论】:
这对我有用
using (var context = new BloggingContext())
{
var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
}
更多信息咨询:https://docs.microsoft.com/es-es/ef/ef6/querying/raw-sql?redirectedfrom=MSDN
【讨论】:
使用它的工作
string strQuery = "SELECT * FROM staff WHERE usertype='lacturer'";
connect.Open();
SqlCommand cmd = new SqlCommand(strQuery, connect);
SqlDataAdapter OleDbDa = new SqlDataAdapter(cmd);
DataSet dsData = new DataSet();
OleDbDa.Fill(dsData);
connect.Close();
std.Text = dsData.Tables[0].Rows.Count.ToString();
【讨论】:
我在自己的应用程序中使用了这种方法来计算程序中的活跃用户数。这可以很容易地为您自己使用。
con.open();
string ActiveUsers = "SELECT * FROM Devices WHERE Status='" + "Online" + "'";
SqlCommand cmd = new SqlCommand(ActiveUsers, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
sda.Fill(ds);
con.Close();
Users.Text = ds.Tables[0].Rows.Count.ToString();
【讨论】: