asp.net代码运行错误!高手帮忙啊!

来源:百度知道 编辑:UC知道 时间:2024/05/27 18:15:16
我在自学asp.net 这是教材里面的例子代码,代码如下:
<%@ Import namespace = "System.Data"%>
<%@ Import namespace = "System.Data.SqlClient"%>
<html>
<head>
<title>ADO.NET</title>
<configuration>
<system.web>
<compilation debug="true"/>
</system.web>
</configuration>
<script Language="C#" runat="server">
public void Page_Load(Object sender,EventArgs e)
{
// 连接到本地计算机的test数据库
String strConn = "server=(local);database=test;uid=sheng;pwd=sheng";
SqlConnection cn = new SqlConnection (strConn);
// 打开连接
cn.Open();
// 构造SQL语句,该语句用于获取姓名为“王莉”的同学的年龄信息
string s ="Select age from Student where name='王莉'" ;
// 创建Command对象
SqlCommand cm = new SqlCommand(s, cn);
// 执行ExecuteScalar()方法
int d = (int)cm. ExecuteScalar();
// 显示年龄信息
Message.

string s ="Select age from Student where name='王莉'" ;
// 创建Command对象
SqlCommand cm = new SqlCommand(s, cn);
// 执行ExecuteScalar()方法
int d = (int)cm. ExecuteScalar();

1.首先 数据库中的age字段一定要是int型的
2.你用ExecuteScalar()只是查询最先一条符合条件的,根本查不来所有的,查所用的要用ExecuteReader()

Server Error in '/test2' Application. 这个服务器控件的代码没有贴出来.

纠正一下,ExecuteScalar()不是“查询最先一条符合条件的”
ExecuteScalar()执行查询,并返回查询所返回的结果集(是所有符合条件的)中第一行的第一列。所有其他的列和行将被忽略。