Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

MySQL values as Dynamic Inputs using C#

Posted on 2013-05-27
6
Medium Priority
?
326 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

 

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

Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

Question has a verified solution.

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

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
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 …
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…

722 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