Why SqlConnection is needed if I can query database using SqlDataAdapter only?

G

goodstart123

For example, the following code works fine without SqlConnection.
Any Answer to the question?

string connectionString =
"server=YourServer; uid=sa;
pwd=YourPassword; database=ProgASPDotNetBugs";

// get records from the Bugs table
string commandString =
"Select BugID, Description from Bugs";

// create the dataset command object
// and the DataSet
SqlDataAdapter dataAdapter =
new SqlDataAdapter(
commandString, connectionString);

DataSet dataSet = new DataSet();

// fill the dataset object
dataAdapter.Fill(dataSet,"Bugs");

// Get the one table from the DataSet
DataTable dataTable = dataSet.Tables[0];

// for each row in the table, display the info
foreach (DataRow dataRow in dataTable.Rows)
{
lbBugs.Items.Add(
dataRow["BugID"] +
": " + dataRow["Description"] );
}
 
M

Morten Wennevik

Hi goodstart123,

What do you mean? You don't need to use an SqlConnection object to use SqlDataAdapter, and overloaded constructor accepts a command string and a connection string just fine. However, there might be a slight benefit of using an existing SqlConnection.
You don't need to use an SqlDataAdapter either if you use SqlConnection and SqlCommand.
 
J

Jon Skeet [C# MVP]

goodstart123 said:
For example, the following code works fine without SqlConnection.
Any Answer to the question?

No, it doesn't work without SqlConnection - it just constructs the
SqlConnection itself from the connection string you give it.
 
J

Joyjit Mukherjee

Hi,

internally, from the connectionstring parameter (third in the SqlDataAdapter
ctor), the DA creates a connection, opens it using the connectionstring
property, fills the DS, closes it. All these is transparent to the end user.

However, if you need to create a DataReader or execute the ExecuteNonQuery
method of the command object, you need to have a connection object.

Regards
Joyjit
 
G

goodstart123

So what is the difference between using and not using SqlConnection?
What kind of benefit?
 
G

goodstart123

What do you mean 'it doesn't work without SqlConnection' ? I am a little confused.
 
J

Jon Skeet [C# MVP]

goodstart123 said:
What do you mean 'it doesn't work without SqlConnection' ? I am a
little confused.

I mean that creating a SqlDataAdapter by passing in the connection
string is basically the same as creating it by passing in a
SqlConnection created with that connection string. The following two
pieces of code are equivalent:

SqlDataAdapter da = new SqlDataAdapter
(command, new SqlConnection(connectionString));

and

SqlDataAdapter da = new SqlDataAdapter(command, connectionString);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top