gpt4 book ai didi

c# - 我不太明白 MySql 连接是什么样的

转载 作者:可可西里 更新时间:2023-11-01 07:59:26 26 4
gpt4 key购买 nike

今天我一直坐在我的电脑前尝试如何连接和使用 MySql 数据库。我有很多问题,但我会尽量只问几个问题。

  1. 当我使用语句 sqlConnection.Open(); 初始化与我的服务器的连接时此连接现在是否已打开并准备好使用,直到我以其他方式通知服务器?

  2. Close() 语句似乎没有关闭连接,如果我查看我的服务器状态,我可以看到发送后连接仍然存在。

  3. 假设我想从我的数据库中检索数据,我首先执行我的函数 setupConnection();此函数发送 Open() 然后返回 true 或 false。然后我可能会有一个函数来检索数据以进行显示和计算等。当我调用这个函数时,我是否需要再次打开连接?

总结一下,连接是否只有在程序与 Open(); 函数处于同一作用域时才打开?

还有我该怎么做才能不必在每个函数中都声明它:

MySqlConnection 连接;sqlConnection = new MySqlConnection();

这是我今天一直在做的一些代码:

    /// <summary>
/// InitConnection outputs the connectionstring
/// </summary>
/// <param name="Adress">Server adress</param>
/// <param name="Port">Server port</param>
/// <param name="Uid">Username</param>
/// <param name="Pwd">Password</param>
/// <param name="Database">Database</param>
/// <returns>the connectionstring</returns>
public string initConnection(string Adress, string Port,
string Uid, string Pwd, string Database)
{
return "server=" + Adress + ";port=" + Port + ";uid=" + Uid + ";" +
"pwd=" + Pwd + ";database=" + Database + ";";
}

/// <summary>
/// setuupConnection will setup an active connection to the database
/// specified in initConnection
/// </summary>
/// <param name="ConnectionString">The return value of
/// initConnection</param>
/// <returns>True or False</returns>
public bool setupConnection(string ConnectionString)
{
MySqlConnection sqlConnection;
sqlConnection = new MySqlConnection();
sqlConnection.ConnectionString = ConnectionString;
try
{
sqlConnection.Open();
return true;
}
catch (MySqlException ex)
{
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server.");
break;
case 1045:
MessageBox.Show("Invalide username/password.");
break;
}
return false;
}
}

/// <summary>
/// closeConnection will terminate the database connection.
/// </summary>
/// <returns>True or False</returns>
public bool closeConnection()
{
MySqlConnection sqlConnection;
sqlConnection = new MySqlConnection();
try
{
sqlConnection.Dispose();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}

最佳答案

您正在设置和关闭功能范围内设置您的连接。你设置你的连接,打开它,然后你的功能结束并且连接超出范围。在您的关闭功能中,您定义的连接只是为了处理它,这是没有意义的。设置您的连接,打开它,使用它,然后关闭它。

看来您应该研究和理解变量作用域。

关于c# - 我不太明白 MySql 连接是什么样的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13778826/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com