我正在使用Visual Studio 2010,我将一个新项目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();
答案 0 :(得分:2)
您必须使用SqlDataReader.Read
将DataReader
推进到下一个数据块:
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);
}
}