我的选择命令不起作用 [英] My select command doesn't work
本文介绍了我的选择命令不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的工作与Visual Studio 2010和我增加了一个新的项目如 report.mdf
来我的项目数据库;我创建了一个表格表1
,我还增加了一个手动记录到表1
;但是当我尝试选择数据我不能做到这一点,出现此错误:
当没有数据是present无效的尝试读取
这是我的code:
的SqlCommand objcomand =新的SqlCommand();
SqlConnection的CON =新的SqlConnection();
con.ConnectionString = @数据源= \ SQLEX $ P $干燥综合征; AttachDbFilename = C:\ Users \用户EHSAN \我的文档\ Visual Studio 2010的\项目\报告\报告\程序App_Data \ report.mdf;集成安全性= TRUE;用户实例=真;
objcomand.Connection = CON;
objcomand.CommandText =选择表1 *;
con.Open();
SqlDataReader的reader1 = objcomand.ExecuteReader();
串I = reader1.GetValue(1)的ToString();
con.Close();
解决方案
您必须提前的DataReader
与 SqlDataReader.Read
一>:
字符串I = NULL;
使用的一切,实现IDisposable像连接或一个DataReader //使用
使用(VAR reader1 = objcomand.ExecuteReader())
{
//因为你的查询循环可以返回多个记录
而(reader1.Read())
{
//如果该字段实际上是第一次,你必须使用的GetString(0)
I = reader1.GetString(1);
}
}
I am working with Visual Studio 2010 and I added a new Item as report.mdf
to my project as database; I created a table Table1
and I have added one record manually to the Table1
; but when I try to select the data I can not do it and get this error:
invalid attempt to read when no data is present
This is my code:
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();
解决方案
You have to advance the DataReader
to the next block of data with SqlDataReader.Read
:
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);
}
}
这篇关于我的选择命令不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文