Databases Reference
In-Depth Information
finally
{
conn.Close();
Console.WriteLine("Connection Closed.");
}
}
}
}
3. Run the program by pressing Ctrl+F5. You should see the output in Figure 11-1.
Figure 11-1. Connecting after creating a command
How It Works
You create a SqlCommand object using the default constructor and print a message indicat-
ing you've created it.
// create SqlCommand
SqlCommand cmd = new SqlCommand();
Console.WriteLine("Command created.");
In this example, the command is empty. It isn't associated with a connection, and it
doesn't have its text (in other words, the SQL) set. You can't do much with it here, so let's
move on and see how you can associate a command with a connection.
Associating a Command with a Connection
For your commands to be executed against a database, each command must be associ-
ated with a connection to the database. You do this by setting the Connection property of
the command, and in order to save resources, multiple commands can use the same con-
nection. You have a couple of ways to set up this association, so next you'll modify the
example to try them.
Search WWH ::




Custom Search