6

我正在尝试使用以下代码连接到我的远程 MySQL 服务器。你能告诉我我做错了什么,因为用变量替换数据库连接信息似乎不起作用。

   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);

作为一名 PHP 开发人员,我更喜欢使用上面的代码,而不是下面的刻意转换:

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

但正如你在这张图片中看到的那样,我得到了很多红色曲线:http: //screencast.com/t/xlwoG9by

4

2 回答 2

10

您的参数顺序错误,应该是:

db_server, db_Name, db_User, db_Pass

目前是:

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

所以你的陈述应该是:

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

编辑:根据评论和讨论,你得到的错误是你在课堂上尝试所有的东西。您应该在方法中包含这些行,并在需要的地方调用该方法。就像是:

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;
    }
}
于 2012-12-19T09:46:50.117 回答
1
 MySqlConnection myConnection = new MySqlConnection(string.Format("server = {0}; database = {1}; uid = {2}; pwd = {3}", db_Server, db_User, db_Pass, db_Name))

string.Format() 丢失

于 2012-12-19T09:48:00.923 回答