Reputation: 69
I wonder why this code didnt work since I already build a method to connect to the database and open the connection. I assume this is because I skip the use of the OleDbCommand Connection
properties. Is it mandatory to use this properties?
My attempt to assign the Connection()
method directly to the OleDbCommand cmd = new OleDbCommand("SELECT City FROM Employees", Connection().Open());
object also didnt work.
using System;
using System.Data;
using System.Data.OleDb;
class KDRM
{
static void Main()
{
OleDbCommand cmd = new OleDbCommand("SELECT City FROM Employees");
Connection().Open();
OleDbDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Console.WriteLine(rdr.GetString(0));
}
Console.ReadLine();
}
public static OleDbConnection Connection()
{
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = "Connection...";
return conn;
}
}
Upvotes: 2
Views: 486
Reputation: 216293
This line
OleDbCommand cmd = new OleDbCommand("SELECT City FROM Employees", Connection().Open());
could not work because you are trying to pass the result of Open as second parameter of the OleDbCommand constructor, but this is a void method so your code doesn't even compile.
Whenever you try to execute a command, you need to set the command connection property, to a valid connection and that connection should be open at the moment in which you execute the command.
There are established good practices to use when creating a connection and you should follow it for a good reason
static void Main()
{
using(OleDbConnection cn = Connection())
using(OleDbCommand cmd = new OleDbCommand("SELECT City FROM Employees", cn);
{
cn.Open();
using(OleDbDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
....
}
}
}
Console.ReadLine();
}
The using statement ensures that the disposable objects in your code are closed and disposed also in case of exceptions.
Upvotes: 2
Reputation: 1793
You should add this kind of code:
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
Upvotes: 1