Skip to content

Instantly share code, notes, and snippets.

@Phuseos
Created June 1, 2017 06:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Phuseos/2ba273eb74f9f1ce9196a720d996cedf to your computer and use it in GitHub Desktop.
Save Phuseos/2ba273eb74f9f1ce9196a720d996cedf to your computer and use it in GitHub Desktop.
Quick method for fetching database information
public static List<string> InfoReturner(List<string> infoToReturn)
{//Load in data based on the string in the List<string>
List<string> ReturnedInfo = new List<string>();
/*
How this works: Create a list that holds the info you want to have.
The list with info obtained will be returned so you can use it like below:
System.Collections.Generic.List<string> GetUserInfo = new System.Collections.Generic.List<string>();
GetUserInfo.Add("Email");
GetUserInfo.Add("Country");
currentClass.UserInfoReturner(GetUserInfo);
Now get the returned info like this:
string Email = ReturnedInfo[0];
string Country = ReturnedInfo[1];
Or simplified (doesn't require creating a new list for the returned info):
string Email = currentClass.InfoReturner(GetUserInfo)[0];
string Country = currentClass.InfoReturner(GetUserInfo)[1];
*/
string AppendedInfo = null; //String that will hold the combined items to return
int l = 0;
{//Append data to the string, to use for inserting in the command
foreach(string Key in infoToReturn)
{
if (l == 0)
{//On the first run, don't add the ","
AppendedInfo = infoToReturn[l];
}
else
{
AppendedInfo = AppendedInfo + ", " + Key;
}
l++;
}
}
using (con) //Set your (My)SQLconnection string here for using
{
//First, get the row count to itterate over
MySqlCommand cmd = new MySqlCommand("SELECT " + AppendedInfo + " FROM yourtable", con);
if (con.State != ConnectionState.Open) con.Open();
using (MySqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
//Itterate over the results
for(int i = 0; i != infoToReturn.Count ; i++)
{
ReturnedInfo.Add(rdr[i].ToString());
}
}
rdr.Close();
}
if (con.State != ConnectionState.Closed) con.Close();
}
return ReturnedInfo; //Now return the list
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment