Reputation: 6723
I have the following ridiculously simple code:
static void Main(string[] args)
{
using (OracleConnection conn = new OracleConnection("Data Source=tnsname;User Id=zzzz;Password=xxxx"))
{
using (OracleCommand cmd = new OracleCommand("SELECT * from CONTRACT"))
{
conn.Open();
IDataReader reader = cmd.ExecuteReader();
}
}
}
}
Obviously I've changed the connection string, but if the connection string is wrong, the conn.Open()
call fails, so I know the connection string is correct, at least as far as the data source, User Id, and Password.
When it gets to the cmd.ExecuteReader()
call, however, I get an InvalidOperationException
with the message, Invalid operation. The connection is closed.
I've done a lot of SQL Server stuff from C#, but this is the first time I've used OracleClient. Can't see anything obviously wrong, other than the fact that it's deprecated, but I'd figure it would still function. I'm not trying to write any production code, I'm just trying to do a little one-off test.
Upvotes: 1
Views: 607
Reputation: 216273
You haven't assigned the Connection instance to the OracleCommand instance
static void Main(string[] args)
{
using (OracleConnection conn = new OracleConnection("Data Source=tnsname;User Id=zzzz;Password=xxxx"))
{
using (OracleCommand cmd = new OracleCommand("SELECT * from CONTRACT", conn))
{
conn.Open();
using(IDataReader reader = cmd.ExecuteReader())
{
.....
}
}
}
}
Just add the conn
instance to the constructor of the command.
By the way, also the reader should be enclosed in a using statement
Upvotes: 1
Reputation: 223207
You haven't associated your connection object with command.
cmd.Connection = conn;
or pass it in Command constructor like:
using (OracleCommand cmd = new OracleCommand("SELECT * from CONTRACT", conn))
Upvotes: 3