Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

MySQL values as Dynamic Inputs using C#

Posted on 2013-05-27
6
Medium Priority
?
334 Views
Last Modified: 2013-05-28
I am trying to create a set of dynamic inputs for fields such as "username" and "password" for a c# application I am writing. Basically, I want to be able and store my username, password, and any other variable I might need to a MySQL database, and have the program call the variables out of that database, rather than hard code them into the program (like they are now). I am finding a lot of information using Connector/Net to modify things on the MySQL end from the C# code, but nothing that really seems like it will apply to what I am trying to do. Anyone have any links or tutorials that might be useful for this sort of thing?
0
Comment
Question by:gbtpgh
  • 3
  • 3
6 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39199591
Is your question how to connect with MySQL from .NET, or how to structure the tables to hold your dynamic values (and subsequently retrieve such values).
0
 

Author Comment

by:gbtpgh
ID: 39199635
Its how to retrieve and use the values in my code.
0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 2000 total points
ID: 39199750
Once you install the .NET connector, you need to add a reference to that assembly. Once you have the reference, for coding ease you can add a using statement to import the namespace. It is simply a matter of opening up a connection to your MySQL database, and then submitting the query.

e.g.

using MySql.Data.MySqlClient;

...

List<KeyValuePair<string, string>> keyValues = new List<KeyValuePair<string, string>>();

using (MySqlConnection con = new MySqlConnection("Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword;"))
{
    using (MySqlCommand cmd = new MySqlCommand("SELECT key, value FROM keyValueTable", con))
    {
        try
        {
            MySqlDataReader reader;

            con.Open();
            reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                keyValues.Add(new KeyValuePair<string, string>(reader["key"].ToString(), reader["value"].ToString()));
            }
        }
        catch (MySqlException ex)
        {
            // handle error
        }
    }
}

// keyValues now contains settings from DB

Open in new window


You can look here for help with the connection string you would use for your database:  http://www.connectionstrings.com/mysql
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 

Author Comment

by:gbtpgh
ID: 39199839
Ok, so, if I have it correct I would substitute "username" and "password" for the values "key" and "value" in that example right? And if that is the case, how would I then be able to integrate them into my later code where I need them, such as in a line like:

private string username = "";
private string password = "";

Also, I did a console.writeline just to verify the information I was getting in keyValues, and I'm assuming something was off here, because what I got was:
System.Collections.Generic.List`1[System.Collections.Generic.KeyValuePair`2[System.String,System.String]]
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 39199927
If I understand the setup you are going for, then no. I got the impression that you were wanting to store key/value pairs in your database, in one table.

e.g.

Key          Value
============ =================
username     jdoe
password     my_secret_phrase
server_name  localhost
start_time   08:00

Open in new window


Then to set username and password in code you would do something like (assuming my previous suggestion is implemented):

// keyValues now contains settings from DB
KeyValuePair<string, string> userpair = keyValues.Find(kv => kv.Key == "username");
string username = userpair.Value;
KeyValuePair<string, string> passpair = keyValues.Find(kv => kv.Key == "password");
string password = passpair.Value;

Open in new window


I used lambda syntax (kv => ...) as a shortcut for the Find method. You could easily loop over the list of items and compare keys until you found the username pair.

What we're doing above is looking through each key/value pair that was stored in the table (what I showed at the beginning of this post). My previous post dealt with pulling in these key/value pairs into the .NET side of things. Now, you have each pair in a list, and you can search that list to find the pair you are interested in (username and password in the example above).

As far as you printing of the values, you saw what you did because by default a Console.WriteLine will print an object using the default ToString implementation for a class, which will print its fully-qualified type name (e.g. the "System.Collections.Generic.List..." stuff you saw output). You need to print out the Value member of each key/value pair that you want to view.

e.g.

KeyValuePair<string, string> passpair = keyValues.Find(kv => kv.Key == "password");

Console.WriteLine(passpair.Value);

Open in new window

0
 

Author Closing Comment

by:gbtpgh
ID: 39201944
Thanks much man! That was exactly what I needed. Worked perfectly!
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
Suggested Courses

876 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question