Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 202
Jeagr Avatar asked Dec 19 '12 09:12

Jeagr


People also ask

What is my database connection string?

Right-click on your connection and select "Properties". You will get the Properties window for your connection. Find the "Connection String" property and select the "connection string". So now your connection string is in your hands; you can use it anywhere you want.

How do I update my connection string?

To edit a connection string for a TableAdapter in a dataset In the Properties window, expand the Connection node. To quickly modify the connection string, edit the ConnectionString property, or click the down arrow on the Connection property and choose New Connection.


1 Answers

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;
    }
}
like image 59
Habib Avatar answered Nov 03 '22 01:11

Habib