Solved

MySQL values as Dynamic Inputs using C#

Posted on 2013-05-27
6
299 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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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
Comment Utility
Its how to retrieve and use the values in my code.
0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
Comment Utility
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:gbtpgh
Comment Utility
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 74

Expert Comment

by:käµfm³d 👽
Comment Utility
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
Comment Utility
Thanks much man! That was exactly what I needed. Worked perfectly!
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

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…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

743 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now