Solved

MySQL values as Dynamic Inputs using C#

Posted on 2013-05-27
6
307 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 500 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 

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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

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

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

831 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