C# 我的select命令没有';行不通
我正在使用VisualStudio2010,我将一个新项目作为C# 我的select命令没有';行不通,c#,sql-server,database,ado.net,C#,Sql Server,Database,Ado.net,我正在使用VisualStudio2010,我将一个新项目作为report.mdf作为数据库添加到我的项目中;我创建了一个表Table1,并手动将一条记录添加到Table1;但是,当我尝试选择数据时,我无法进行选择,并出现以下错误: 不存在数据时读取的尝试无效 这是我的代码: SqlCommand objcomand = new SqlCommand(); SqlConnection con = new SqlConnection(); con.ConnectionString=@"Data
report.mdf
作为数据库添加到我的项目中;我创建了一个表Table1
,并手动将一条记录添加到Table1
;但是,当我尝试选择数据时,我无法进行选择,并出现以下错误:
不存在数据时读取的尝试无效
这是我的代码:
SqlCommand objcomand = new SqlCommand();
SqlConnection con = new SqlConnection();
con.ConnectionString=@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\EHSAN\My Documents\Visual Studio 2010\Projects\report\report\App_Data\report.mdf;Integrated Security=True;User Instance=True";
objcomand.Connection = con;
objcomand.CommandText = "select * from Table1";
con.Open();
SqlDataReader reader1 = objcomand.ExecuteReader();
string i = reader1.GetValue(1).ToString();
con.Close();
您必须使用以下命令将
DataReader
前进到下一个数据块:
好的,我说我已经手动在我的表中添加了一个字段,所以reader.read()应该是真的!所以我没有用它。我说得对吗?@sarahsh-没错,它不仅返回真值;它还将
SqlDataReader
提升到其结果中的第一条记录。是的,我真的不知道这很重要,对我来说太激动了!非常感谢。@sarahsh:因为您的查询可能返回多条记录,所以我使用了while
循环。您应该使用列表
或列表
(其中CustomType
是一个自制类),并在循环中向其添加项目。否则,您将始终使用下一个值覆盖上一个值。
string i = null;
// use using for everything that implements IDisposable like a Connection or a DataReader
using(var reader1 = objcomand.ExecuteReader())
{
// a loop since your query can return multiple records
while(reader1.Read())
{
// if the field actually is the first you have to use GetString(0)
i = reader1.GetString(1);
}
}