/// <summary>
/// 跟据条件查询记录的数量
/// </summary>
/// <returns></returns>
public int SearchBookNum(string condition)
{
int total = 0;
string sql = "select sum(你的字段) from 表名 where 条件" ;
SqlConnection conn = null;
try
{
conn = ConnectionManager.GetConnection();
conn.Open();
//获取SqlCommand,封装sql
SqlCommand command = new SqlCommand(sql, conn);
//发送SQL,结果是SqlDataReader类型
total = Convert.ToInt32(command.ExecuteScalar());//ExecuteScalar()用于查询单行单列,同于count()
}
catch (SqlException)
{
throw new DAOException();
}
finally
{
if (conn != null)
{
conn.Close();
}
}
return total;
}
肯定会报错的啊,我写的只是一个列子,你要参照我写的这种方式,把你的连接数据库写上吧,我的连接数据库是这样的:
class ConnectionManager
{
/// <summary>
/// 获取数据库连接
/// </summary>
/// <returns></returns>
public static SqlConnection GetConnection()
{
string connStr = @"Data Source=WIN-20120404HSE;Initial Catalog=BooksManage;Integrated Security=True";
return new SqlConnection(connStr);
}
}
你要改成你自己的连接。
广告 您可能关注的内容 |