dataReader reader = cmd.executereader()无法正常工作

时间:2016-02-18 00:48:28

标签: c# sql .net winforms visual-studio-2012

我陷入了简单的datareader问题。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.Sql;

public void proName(string str)
        {
            SqlDataReader reader;
             using (SqlConnection sqlcon = new SqlConnection(constr))
            {
               string proId = textBox3.Text;

               SqlCommand sqlcmd = new SqlCommand("SELECT proName FROM products where proId = proId;", sqlcon);
               sqlcmd.CommandType = CommandType.TableDirect;
               reader = cmd.executereader();


            }
        }

并且在cmd / command下显示错误(名称cmd在当前上下文中不退出).....

我在连接之前和之后尝试过创建对象但没有工作。

3 个答案:

答案 0 :(得分:4)

命令类型不应为TableDirect

sqlcmd.CommandType = CommandType.Text; // which is default
reader = sqlcmd.executereader();

答案 1 :(得分:1)

变量名称为sqlcmd,您在cmd函数上要求executereader()

sqlcmd.CommandType = CommandType.TableDirect;
reader = cmd.executereader();

应该是

sqlcmd.CommandType = CommandType.TableDirect;
reader = sqlcmd.executereader();

还要考虑CharithJ的答案,正如他所说:

  

命令类型不应该是TableDirect。

答案 2 :(得分:1)

下面应该工作..

using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using System.Data.Sql;
        public void proName(string str)
        {
            SqlDataReader reader;
            using (SqlConnection sqlcon = new SqlConnection(constr))
            {
                string proId = textBox3.Text;
                sqlcon.Open();
                SqlCommand sqlcmd = new SqlCommand("SELECT proName FROM products where proId = proId;", sqlcon);
                sqlcmd.CommandType = CommandType.Text;
                reader = sqlcmd.ExecuteReader();
                if (reader.Read())
                {
                    Response.Write(reader[0].ToString());

                }

            }
        }