Skip to content

Instantly share code, notes, and snippets.

@jak
Created February 14, 2011 17:20
Show Gist options
  • Save jak/826196 to your computer and use it in GitHub Desktop.
Save jak/826196 to your computer and use it in GitHub Desktop.
c# accessing database example
public List<String> GetFirstNames(string surname) {
List<String> names = new List<String>();
using (SqlConnection con = new SqlConnection(<connection string>)) {
using (SqlCommand cmd = new SqlCommand("SELECT firstname FROM People WHERE surname=@surname", con)) {
cmd.Parameters.AddWithValue("@surname", surname);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read()) { // while there is data
string name = reader["firstname"].ToString(); // for other data, use Convert.ToInt32() etc
names.Add(name);
}
}
}
return names;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment