As long as your project references System.Data - and it should by default unless you have used an "odd" project template, then all you need to use is check the .CS file and make sure you have both of these lines at the top of the file:
using System.Data;
using System.Data.SqlClient;
If those lines aren't showing any error (i.e. none of it is underlined in red) then you can use the
SqlConnection
,
SqlCommand
, and suchlike very easily:
using (SqlConnection con = new SqlConnection(strConnect))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT Id, description FROM myTable", con))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int id = (int) reader["Id"];
string desc = (string) reader["description"];
Console.WriteLine("ID: {0}\n {1}", id, desc);
}
}
}
}
If any of that code is underlined in red (except for the connection string in the first line) then you have a problem.
Other than that, you don't strictly need
using
lines for System.Data or System.Data.SqlClient: you can give the full class name every time you use them:
using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strConnect))
{
con.Open();
using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand("SELECT Id, description FROM myTable", con))
{
using (System.Data.SqlClient.SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int id = (int)reader["Id"];
string desc = (string)reader["description"];
Console.WriteLine("ID: {0}\n {1}", id, desc);
}
}
}
}
Adding the
using
statements just reduces the typing and makes it more readable, is all.