VerySource

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
12
返回列表 发新帖
楼主: raofeng76

关于asp.NET中不能把SqlDataReader返回值赋给变量的问题,着急啊,请高手给看看!

[复制链接]

0

主题

16

帖子

13.00

积分

新手上路

Rank: 1

积分
13.00
发表于 2020-1-31 11:18:01 | 显示全部楼层
cmd=new SqlCommand("select * from users where userID="+userID+"",cnn);

语法有错误!

少了引号!!!

cmd=new SqlCommand("select * from users where userID= '"+userID+"'",cnn);
回复

使用道具 举报

0

主题

119

帖子

67.00

积分

新手上路

Rank: 1

积分
67.00
发表于 2020-1-31 14:54:01 | 显示全部楼层
private static void ReadOrderData(string connectionString)
{
    string queryString ="SELECT OrderID, CustomerID FROM dbo.Orders";//查询语句
    string str1="";
    string str2="";
    using (SqlConnection connection =new SqlConnection(connectionString))
    {
        SqlCommand command =new SqlCommand(queryString, connection);//构造Command
        connection.Open();//打开连接

        SqlDataReader reader = command.ExecuteReader();//生成DataReader

        if(reader.Read())//用循环依次读取数据
        {
//将数据赋值
            str1=reader[0].ToString();
            str2=reader[1].ToString();            
        }
        reader.Close();//关闭Reader
    }
}
回复

使用道具 举报

1

主题

8

帖子

5.00

积分

新手上路

Rank: 1

积分
5.00
 楼主| 发表于 2020-1-31 15:18:01 | 显示全部楼层

郁闷,又出现新的错了!

在没有任何数据时进行无效的读取尝试。
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。

异常详细信息: System.InvalidOperationException: 在没有任何数据时进行无效的读取尝试。

源错误:


行 19:        SqlDataReader dr=cmd.ExecuteReader(CommandBehavior.CloseConnection);
行 20:        dr.Read();
行 21:        Label1.Text=dr.GetString(0);
行 22:        TextBox1.Text=dr.GetString(1);
行 23:        TextBox2.Text=dr.GetString(2);


回复

使用道具 举报

0

主题

16

帖子

13.00

积分

新手上路

Rank: 1

积分
13.00
发表于 2020-1-31 21:00:01 | 显示全部楼层
过去写的一个东西,一段代码:

public void table_fill()
{
SqlConnection conn=new SqlConnection("data source=fish_in_sky;database=MIS;uid=sa;pwd=");
SqlCommand myCommand=new SqlCommand();
conn.Open();
string strsql = "select 真实姓名,身份证号,地址,电话,Email,备注 from user_info where 用户名='" + Request.QueryString["name"] + "'";
SqlCommand cmd = new SqlCommand(strsql, conn);
SqlDataReader rd = cmd.ExecuteReader();
if (rd.Read())
{
TextBox4.Text=rd.GetValue(0).ToString().Trim();
TextBox5.Text=rd.GetValue(1).ToString().Trim();
TextBox6.Text=rd.GetValue(2).ToString().Trim();
TextBox7.Text=rd.GetValue(3).ToString().Trim();
TextBox8.Text=rd.GetValue(4).ToString().Trim();
TextBox9.Text=rd.GetValue(5).ToString().Trim();
}
conn.Close();
}
回复

使用道具 举报

1

主题

8

帖子

5.00

积分

新手上路

Rank: 1

积分
5.00
 楼主| 发表于 2020-2-1 02:36:01 | 显示全部楼层
感谢大家!一切解决了!
这东西关键:Label1.Text=dr.GetValue(0).ToString().Trim();
如果是Label1.Text=dr.GetString(0)会出现以下错误:
指定的转换无效。
说明: 执行当前 Web 请求期间,出现未处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。
异常详细信息: System.InvalidCastException: 指定的转换无效。

再次感谢大家!


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|CopyRight © 2008-2023|verysource.com ( 京ICP备17048824号-1 )

快速回复 返回顶部 返回列表