c# – 此数据库连接字符串有什么问题?

前端之家收集整理的这篇文章主要介绍了c# – 此数据库连接字符串有什么问题?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用以下代码连接到我的远程 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

解决方法

您的参数顺序错误,应该是:
db_server,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_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_Pass));
        return myConnection;
    }
}

猜你在找的C#相关文章