Retrieving table data from SQL Server using C#
This is a simple task which can be accomplished with below code. Below code is useful to retrieve table data from SQL Server using C#.net .
public List<Contact> LoadContacts()
{
List<Contact> ContactDetails= new List<Contact>();
string selectQuery = "SELECT * FROM Contact";
SqlConnection connection = new SqlConnection("Data Source=(local); Initial Catalog = DataBaseName; Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand(selectQuery , connection );
try
{
connection.Open();
SqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Contact contact = new Contact();
contact.ID = Convert.ToInt32(dataReader["ID"]);
contact.Name = dataReader["Name"].ToString();
contact.EmailID = dataReader["EmailID"].ToString();
contact.Mobile = dataReader["Mobile"].ToString();
contact.LandLine = dataReader["LandLine"].ToString();
contact.WebSite = dataReader["WebSite"].ToString();
contact.Address = dataReader["Address"].ToString();
ContactDetails.Add(contact);
}
dataReader.Close();
}
catch(Exception e)
{ }
finally
{
connection .Close();
}
return ContactDetails;
}
Connection string's options :
public List<Contact> LoadContacts()
{
List<Contact> ContactDetails= new List<Contact>();
string selectQuery = "SELECT * FROM Contact";
SqlConnection connection = new SqlConnection("Data Source=(local); Initial Catalog = DataBaseName; Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand(selectQuery , connection );
try
{
connection.Open();
SqlDataReader dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Contact contact = new Contact();
contact.ID = Convert.ToInt32(dataReader["ID"]);
contact.Name = dataReader["Name"].ToString();
contact.EmailID = dataReader["EmailID"].ToString();
contact.Mobile = dataReader["Mobile"].ToString();
contact.LandLine = dataReader["LandLine"].ToString();
contact.WebSite = dataReader["WebSite"].ToString();
contact.Address = dataReader["Address"].ToString();
ContactDetails.Add(contact);
}
dataReader.Close();
}
catch(Exception e)
{ }
finally
{
connection .Close();
}
return ContactDetails;
}
Connection string's options :
- Integrated Security=SSPI; – This means we want to connect using Windows authentication.
- Initial Catalog=DataBaseName; – This means the database we want to first connect to is named “DataBaseName”.
- Data Source=(local); – This means that we want to connect to the SQL Server instance located on the local machine.
No comments:
Post a Comment