What happened to this database connection string?

I am trying to connect to a remote MySQL server using the following code. Can you tell me what I am doing wrong, since replacing database connection information with variables does not work.

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 above code instead of intentionally 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 get a lot of red squiggles: http://screencast.com/t/xlwoG9by

+6
source share
3 answers

The order of your parameter is incorrect, it must 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 get is that you are trying to use all the materials at the class level. You should have these lines inside the method and call this method where you need it. Sort of:

 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; } } 
+10
source

Could you click this link, it solves everything about creating the MySql Server connection string :)

+2
source
  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

+1
source

All Articles