当前位置: 代码迷 >> ASP.NET >> 求指教“ExecuteScalar”显示表行数的有关问题
  详细解决方案

求指教“ExecuteScalar”显示表行数的有关问题

热度:1972   发布时间:2013-02-25 00:00:00.0
求指教“ExecuteScalar”显示表行数的问题


程序如下:
目的是在Label1中显示该表的行数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
  SqlConnection con = new SqlConnection("Data Source=yh-20120602uzvz\\SQLNEW;Initial Catalog=guestbook;Integrated Security=True");

  SqlCommand comm = new SqlCommand("select count(*)from GuestBook", con);
  con.Open();
  int count = (Int32)comm.ExecuteScalar();
  Label1.Text = count.ToString();
  con.Close();
  }
}


调试后报错:“int count = (Int32)comm.ExecuteScalar();附近有语法错误”(调试前无错误显示)

------解决方案--------------------------------------------------------
2楼的写法规范一点吧,虽然你的返回结果肯定是>=0的一个数字,如果是调试的时候编译通不过,应该是写法不规范,如果是编译可以通过但运行时报错,那应该是具体转换时,出了问题了。
我觉得你的问题应该是前者吧,编译没有通过。。。。
------解决方案--------------------------------------------------------
很简单,这不是类型转换不对,仔细看:
qlCommand comm = new SqlCommand("select count(*)from GuestBook", con);

中的sql语句,count(*)这部分的左右括号不匹配,可能一个是中文的括号。