c# - SqlConnection State is always Closed at Execution -
i trying create simple ms access database connection using sqlconnection , sqlcommand objects.
as can see here how create connection:
private sqlconnection getconnection() { string connstr = configurationmanager.connectionstrings[0].connectionstring; sqlconnection conn = new sqlconnection(connstr); homecoming conn; } and before ask, yes have tried move piece of code method calls it. didn't alter anything. still reads connection string wrong.
the connection string looks , located in app.config file:
<add name="connstring" connectionstring="server=*.*.*.*;database=familie;user id=mfs;password=********;"/> but when error:
and @ connection string object @ time, string looks this:
"data source=.\\sqlexpress;integrated security=sspi;attachdbfilename=|datadirectory|aspnetdb.mdf;user instance=true" i have spent 2 hours trying create work, going many different sites figure out did wrong, either info is old, conflicting or deals connecting local database, when in fact external 1 access through proxy given me client (trustgate if should ask)
the method calls getconnection() looks this:
public dictionary<int,string> getpostnrlist() { sqlconnection conn = getconnection(); sqlcommand cmd = new sqlcommand("execute dbo.hent_post_nr_liste", conn); var reader = cmd.executereader(); dictionary<int, string> liste = new dictionary<int, string>(); while (reader.nextresult()) { int post_nr = (int) reader.getsqlint32(0); string = reader.getstring(1); liste.add(post_nr, by); } closeconnection(conn); homecoming liste; } what doing wrong?
the exception message tells problem - connection not open. need open connection prior executing command:
conn.open(); btw, pattern using using block when dealing sql connections, ensure gets disposed properly:
using (var conn = getconnection()) { using (var comm = xxxxxxx) { conn.open(); using (var rdr = comm.executereader()) { // xxxxx } } } you don't have close - using pattern you.
c# sql ms-access
No comments:
Post a Comment