我陷入了简单的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在当前上下文中不退出).....
我在连接之前和之后尝试过创建对象但没有工作。
答案 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());
}
}
}