数据表:Login
userID userName userPwd Dept
1 kang Admin 信部
2 DaLing Ling 总经办
private void Page_Load(object sender, System.EventArgs e)
{
SqlConnection con=new SqlConnection("server=.;database=aico;uid=sa;pwd=sa");
con.Open();
SqlCommand cmd=new SqlCommand("select * from Login where userID="+1,con);
SqlDataReader myReader=cmd.ExecuteReader();
Response.Write(myReader["userID"].ToString());
// 在此处放置用户代码以初始化页面
}
提示如下错误:
在没有任何数据时进行无效的读取尝试。
userID userName userPwd Dept
1 kang Admin 信部
2 DaLing Ling 总经办
private void Page_Load(object sender, System.EventArgs e)
{
SqlConnection con=new SqlConnection("server=.;database=aico;uid=sa;pwd=sa");
con.Open();
SqlCommand cmd=new SqlCommand("select * from Login where userID="+1,con);
SqlDataReader myReader=cmd.ExecuteReader();
Response.Write(myReader["userID"].ToString());
// 在此处放置用户代码以初始化页面
}
提示如下错误:
在没有任何数据时进行无效的读取尝试。
还有就是
SqlDataReader myReader=cmd.ExecuteReader();
后面还要写上:
while(myReader.Read())
{
Response.Write(myReader["userID"].ToString());}
{
SqlConnection con=new SqlConnection("server=.;database=aico;uid=sa;pwd=sa");
con.Open();
SqlCommand cmd=new SqlCommand("select * from Login where userID="+1,con);
SqlDataReader myReader=cmd.ExecuteReader();
if(myReader != null)
{
Response.Write(myReader["userID"].ToString());
}
// 在此处放置用户代码以初始化页面
}
SqlCommand cmd=new SqlCommand("select * from Login where userID=1",con);
应该是
if ( r.Read())
加上myReader.Read();
2.用SqlDataReader 最好捕捉异常
{
Response.Write(myReader["userID"].ToString());
}
{
Response.Write(myReader["userID"].ToString());
}
这句话错了吧
应该是SqlCommand cmd=new SqlCommand("select * from Login where userID=1,con);
阿
还有就是
SqlDataReader myReader=cmd.ExecuteReader();
后面还要写上:
while(myReader.Read())
{
Response.Write(myReader["userID"].ToString());}
-------------------------正解
if (myReader.Read())
{
Response.Write(myReader["userID"].ToString());
}
必须myReader.Read()才会读取一行数据,然后就可以通过myReader["userID"]获取字段数据了
Response.Write(myReader["userID"].ToString())
con.Open();
SqlCommand cmd=new SqlCommand("select * from Login where userID="+"1",con);//数据类型
SqlDataReader myReader=cmd.ExecuteReader();
myReader.Read();//开始读取
Response.Write(myReader["userID"].ToString());
myReader.Close();//关闭读取器
con.Close();//关闭连接
{
Response.Write(myReader["userID"].ToString());}