Solved

MySQL values as Dynamic Inputs using C#

Posted on 2013-05-27
6
317 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 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
Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

 

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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

752 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