我正在尝试使用以下代码连接到我的远程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
答案 0 :(得分: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;
}
}
答案 1 :(得分:2)
你是否介意点击这个link,它解决了MySql Server连接字符串的创建问题:)
答案 2 :(得分: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()