我正在使用用户输入数据库连接信息的表单,然后将其存储在类dbConStr
中的多个字符串中,然后从实际连接表单构建和引用。
这是类文件:
class dbConStr
{
public static String strServer;
public static String strPort;
public static String strDatabase;
public static String strUid;
public static String strPwd;
public static String strConnect = strServer + strPort + strDatabase + strUid + strPwd;
}
这是将值分配给字符串的按钮:
private void btnStoreCon_Click(object sender, EventArgs e)
{
dbConStr.strServer = "Server="+txtServer.Text+";";
dbConStr.strPort = "Port=" + txtPort.Text + ";";
dbConStr.strDatabase = "Database=" + txtDatabase.Text + ";";
dbConStr.strUid = "Uid=" + txtUsername.Text + ";";
dbConStr.strPwd = "Pwd=" + txtPassword.Text + ";";
}
我收到的错误是无法连接到指定的MySQL主机。
答案 0 :(得分:3)
您可以使用MySqlConnectionStringBuilder创建连接字符串。
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "localhost";
conn_string.UserID = "user";
conn_string.Password = "password";
conn_string.Database = "test_db";
var connectionString = conn_string.ToString();
或尝试这样的事情:
class dbConStr
{
public static String strServer;
public static String strPort;
public static String strDatabase;
public static String strUid;
public static String strPwd;
public static string ConnectionString
{
MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = dbConStr.strServer;
conn_string.UserID = dbConStr.strUid;
conn_string.Password = dbConStr.strPwd;
conn_string.Database = dbConStr.strDatabase;
conn_string.Port = dbConStr.strPort;
return conn_string.ToString();
}
}
答案 1 :(得分:0)
你需要
using MySql.Data.MySqlClient;
private void btnStoreCon_Click(object sender, EventArgs e)
{
MySqlConnection connection;
string server;
string database;
string uid;
string password;
server = txtServer.Text;
database = txtDatabase.Text;
uid = txtUsername.Text;
password =txtPassword.Text;
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
更多信息可以在http://www.codeproject.com/Articles/43438/Connect-C-to-MySQL
找到答案 2 :(得分:0)
private void btnStoreCon_Click(object sender, EventArgs e)
{
dbConStr.strServer = "Server=" + txtServer.Text + ";";
dbConStr.strPort = "Port=" + txtPort.Text + ";";
dbConStr.strDatabase = "Database=" + txtDatabase.Text + ";";
dbConStr.strUid = "Uid=" + txtUsername.Text + ";";
dbConStr.strPwd = "Pwd=" + txtPassword.Text + ";";
dbConStr.strConnect = dbConStr.strServer + dbConStr.strPort + dbConStr.strDatabase + dbConStr.strUid + dbConStr.strPwd;
}
我需要在按钮点击事件
中创建字符串