读书人

求指教“ExecuteScalar”显示表行数的

发布时间: 2012-09-09 09:27:54 作者: rapoo

求指教“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(*)这部分的左右括号不匹配,可能一个是中文的括号。

读书人网 >asp.net

热点推荐