Jeagr
Jeagr

Reputation: 1058

What is wrong with this Database connection string?

I am trying to connect to my remote MySQL server, using the following code. Can you tell me what I am doing wrong as the replacement of database connection info with variables doesn't seem to be working.

   using MySql.Data.MySqlClient;       

   string db_Server = "10.0.0.0";
   string db_Name   = "myDatabase";
   string db_User   = "myUser";
   string db_Pass   = "myPassword";


   // Connection String
   MySqlConnection myConnection = new MySqlConnection("server = {0}; database = {1}; uid = {2}; pwd = {3}", db_server, db_Name, db_User, db_Pass);

As a PHP developer, I prefer to use the code above instead of the deliberate casting below:

   MySqlConnection myConnection = new MySqlConnection("server=10.0.0.0; database=myDatabase; uid=myUser; pwd=myPassword");

But as you can see in this image, I am getting a lot of red squiggles: http://screencast.com/t/xlwoG9by

Upvotes: 6

Views: 1028

Answers (2)

Habib
Habib

Reputation: 223267

Order of your parameter is wrong, it should be:

db_server, db_Name, db_User, db_Pass

Currently it is:

"server = {0}; database = {1}; uid = {2};   pwd = {3}"
       db_Server         db_User   db_Pass   db_Name

So your statement should be:

MySqlConnection myConnection = new MySqlConnection(string.Format(
"server = {0}; database = {1}; uid = {2}; pwd = {3}", 
db_Server,db_Name, db_User, db_Pass));

EDIT: based on the comments and discussion, the error you are getting is that you are trying all the stuff at class level. You should have these lines inside a method and call that method where you need it. Something like:

class MyClass
{
    string db_Server = "10.0.0.0";
    string db_User = "myUser";
    string db_Pass = "myPassword";
    string db_Name = "myDatabase";


    public MySqlConnection GetConnection()
    {
        MySqlConnection myConnection = new MySqlConnection(string.Format(
                   "server = {0}; database = {1}; uid = {2}; pwd = {3}",
                    db_Server, db_Name, db_User, db_Pass));
        return myConnection;
    }
}

Upvotes: 10

Daniel W.
Daniel W.

Reputation: 449

 MySqlConnection myConnection = new MySqlConnection(string.Format("server = {0}; database = {1}; uid = {2}; pwd = {3}", db_Server, db_User, db_Pass, db_Name))

string.Format() is missing

Upvotes: 1

Related Questions