sql server - SqlDataReader.Read Not Working As Advertised? -
so i'm running query in ado.net know returns single row. relevant portion of code looks like:
sqlcommand sqc = new sqlcommand(); sqc.connection = new sqlconnection("connection string"); sqc.commandtext = "select a, b c d=@d"; sqc.parameters.addwithvalue("@d", "d"); sqc.connection.open(); sqldatareader rdr = sqc.executereader(); bool boolio = rdr.read(); string = (string)rdr["a"]; when run this, exception on final line, complaining i'm trying read there's no data.
when step through in vs inspect rdr before rdr.read() line executes , can see data want sitting in reader. call rdr.read() , result false, indicating there no more data me read. when inspect rdr again, internal resultsview empty.
i realize can data discarding call read() but: behaviour contrary msdn documentation explicitly says "the default position of sqldatareader before first record. therefore, must call read begin accessing data.". contrary every example of sqldatareader usage i've found on web such this question seems exist taunt me.
note i've tested code against .net 3.5 , .net 4.5 identical results.
am missing something? there bug in ado.net? input appreciated!
update 1: actual exception on last line is:
an unhandled exception of type 'system.invalidoperationexception' occurred in system.data.dll
additional information: invalid attempt read when no data present.
update 2:
because nathan skerl unable reproduce behavior, , posted verified working code subsequently failed me, suspect there may issue platforms we're running on. record using windows 7 professional (64-bit) service pack 1 , have compiled project against .net framework 3.5 , 4.5 same results. if there relevant information have failed include please let me know , add it.
update: after troubleshooting realized reader empty due inspecting reader in debugger expanding results view (which calls read() , consumes rows).
using code ran unit test in linqpad , results expected, initial reader.read() advances row "one", , second call row "two". can reproduce error test such this:
sqlcommand sqc = new sqlcommand(); sqc.connection = (sqlconnection)this.connection; sqc.commandtext = "select 'one' [a] union select 'two' order [a] asc;"; sqc.parameters.addwithvalue("@d", "d"); sqc.connection.open(); sqldatareader rdr = sqc.executereader(); bool boolio = rdr.read(); string = (string)rdr["a"]; a.dump(); rdr.read(); string b = (string)rdr["a"]; b.dump(); can show pattern returns:
using (sqlconnection connection = (sqlconnection)this.connection) using (sqlcommand sqc = new sqlcommand("select 'one' [a] union select 'two';", connection)) { connection.open(); using (sqldatareader rdr = sqc.executereader()) { while (rdr.read()) { console.writeline(string.format("{0}", (string)rdr["a"])); } } }
Comments
Post a Comment