从SQL查询中捕获计数

时间:2011-01-12 12:40:57

标签: c# sql sql-server

C#(.cs文件)中从SQL命令获取计数的最简单方法是什么

SELECT COUNT(*) FROM table_name

进入int变量?

5 个答案:

答案 0 :(得分:93)

使用SqlCommand.ExecuteScalar()并将其投放到int

cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();

答案 1 :(得分:19)

SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = (Int32) comm .ExecuteScalar();

答案 2 :(得分:9)

您将通过以下方式转换错误:

cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();

改为使用:

string stm = "SELECT COUNT(*) FROM table_name WHERE id="+id+";";
MySqlCommand cmd = new MySqlCommand(stm, conn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
if(count > 0){
    found = true; 
} else {
    found = false; 
}

答案 3 :(得分:1)

使用SQL补充C#:

SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = Convert.ToInt32(comm.ExecuteScalar());
if (count > 0)
{
    lblCount.Text = Convert.ToString(count.ToString()); //For example a Label
}
else
{
    lblCount.Text = "0";
}
conn.Close(); //Remember close the connection

答案 4 :(得分:0)

 **html code**
<form id="form" enctype="multipart/form-data">
<label>Image:</label>
<input type="file" name="txtimg">
<input type="submit" value="INSERT IMAGE" name="btnimage">
</form>
<div id="message"></div>


**ajax request**
<script type="text/javascript">
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
  url: "upload.php",   
  type: "POST",             
  data:  new FormData(this),   
  contentType: false,          
      cache: false,         
  processData:false,        
  success: function(data)     
    {
      $("#message").html(data);     
    }         
 });
 }));
 });