Tuesday, 15 January 2013

sql server - Adding elements to a list with SQL query and .NET -



sql server - Adding elements to a list with SQL query and .NET -

i new writing console applications, , escaping me on how this.

what trying take query string, turn product_type_no ptn, add together each ptn list named ptnlist. there on 1200 ptn's, , can run sql query in ms sql server , info need, know query fine.

when step through code, seems break right before 'while (rdr.read())', jumping downwards 'catch', giving invalidoperationexception stating 'executereader: connection property has not been initialized.'

like said, i'm rather new this, may sound basic problem me not catch, help appreciated.

below s snippet of code, part giving me problem.

try { const string connectionstring = "connectioninfo"; con = new sqlconnection(connectionstring); con.open(); //connect db ptn product_type_def string query = @"select product_type_no ptn dbo.product_type_def"; list<int> ptnlist = new list<int>(); sqlcommand cmd = new sqlcommand(query); rdr = cmd.executereader(); while (rdr.read()) { ptnlist.add(convert.toint32("ptn")); } }

a few different problems there. firstly, didn't tell command connection. second, aren't reading reader @ end. connection can set either passing connection constructor:

sqlcommand cmd = new sqlcommand(query, con);

or calling:

cmd.connection = con;

to read actual data, want like:

ptnlist.add(rdr.getint32(0));

note command, connection , reader idisposable , should using using.

alternatively, utilize tool "dapper" help you:

using(var con = new sqlconnection(connectionstring)) { var ptnlist = con.query<int>(query).tolist(); }

.net sql-server list

No comments:

Post a Comment