Skip to content

Instantly share code, notes, and snippets.

@appforest
Created January 5, 2014 17:26
Show Gist options
  • Save appforest/8271098 to your computer and use it in GitHub Desktop.
Save appforest/8271098 to your computer and use it in GitHub Desktop.
Writing data to a variable from a DB query using a SqlDataReader
[WebMethod]
public static string GetValues2(string value)
{
string CS = ConfigurationManager.ConnectionStrings["test_connectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
con.Open(); // The connection needs to be explicitly opened in order to use the SqlDataReader.
SqlCommand cmd = new SqlCommand("SELECT * FROM something WHERE somethingId = 2", con);
using (SqlDataReader rdr = cmd.ExecuteReader()) // Cannot be instantiated with the 'new' operator. Needs an open connection.
{
while (rdr.Read())
{
column = (string)rdr["somethingName"];
}
} return column;
}
}
public static string column { get; set; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment