今天我一直坐在我的电脑前,尝试如何连接和使用 MySql 数据库。我有很多问题,但我会尽量保留几个。
当我使用语句初始化与服务器的连接时,
sqlConnection.Open();
此连接现在是否打开并准备好使用,直到我告诉服务器否则?该
Close()
语句似乎没有关闭连接,如果我查看我的服务器状态,我可以看到我发送后连接仍然存在。假设我想从我的数据库中检索数据,我首先执行我的函数
setupConnection();
This fuuction 发送Open()
,然后返回 true 或 false。然后我可能会有一个函数来检索数据以进行显示和计算等。当我调用这个函数时,我需要再次打开连接吗?
稍微总结一下,是不是程序和Open();
函数在同一个作用域时才打开连接?
还有我能做些什么来不必在每个函数中声明这个:
MySqlConnection sqlConnection; 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;
}
}