Reputation:
I need to learn ADO.NET to build applications based on MS Office. I have read a good deal about ADO.NET in the MSDN Library, but everything seems rather messy to me.
What are the basics one must figure out when using ADO.NET? I think a few key words will suffice to let me organize my learning.
Upvotes: 17
Views: 1238
Reputation: 99957
Another way of getting a command object is to call connection.CreateCommand()
.
That way you shouldn't have to set the Connection
property on the command object.
Upvotes: 0
Reputation: 21844
There are three key components (assuming ur using SQL server):
SQLConnection
SqlCommand
SqlDataReader
(if you're using something else, replace Sql
with "Something", like MySqlConnection
, OracleCommand
)
Everything else is just built on top of that.
Example 1:
using (SqlConnection connection = new SqlConnection("CONNECTION STRING"))
using (SqlCommand command = new SqlCommand())
{
command.commandText = "SELECT Name FROM Users WHERE Status = @OnlineStatus";
command.Connection = connection;
command.Parameters.Add("@OnlineStatus", SqlDbType.Int).Value = 1; //replace with enum
connection.Open();
using (SqlDataReader dr = command.ExecuteReader))
{
List<string> onlineUsers = new List<string>();
while (dr.Read())
{
onlineUsers.Add(dr.GetString(0));
}
}
}
Example 2:
using (SqlConnection connection = new SqlConnection("CONNECTION STRING"))
using (SqlCommand command = new SqlCommand())
{
command.commandText = "DELETE FROM Users where Email = @Email";
command.Connection = connection;
command.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = "[email protected]";
connection.Open();
command.ExecuteNonQuery();
}
Upvotes: 6