C4d*_*C4d 1 c# mysql connection database-connection
首先:我在不使用oop的情况下运行代码.我在同一个类中声明了所有变量,并在将查询传递给db之前和之后打开/关闭了连接.那很有效!现在有了一些新的经验,我试图将我的代码分成不同的类.现在它不再工作了.
它告诉我"连接必须有效且开放".足够的文字,这是我目前的代码:
Services.cs
public static MySqlConnection conn // Returns the connection itself
{
get
{
MySqlConnection conn = new MySqlConnection(Services.ServerConnection);
return conn;
}
}
public static string ServerConnection // Returns the connectin-string
{
get
{
return String.Format("Server={0};Port=XXXX;Database=xxx;Uid=xxx;password=xxXxxXxXxxXxxXX;", key);
}
}
public static void DB_Select(string s, params List<string>[] lists)
{
try
{
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
string command = s;
cmd.CommandText = command;
MySqlDataReader sqlreader = cmd.ExecuteReader();
while (sqlreader.Read())
{
if (sqlreader[0].ToString().Length > 0)
{
for (int i = 0; i < lists.Count(); i++)
{
lists[i].Add(sqlreader[i].ToString());
}
}
else
{
foreach (List<string> save in lists)
{
save.Add("/");
}
}
}
sqlreader.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error while selecting data from database!\nDetails: " + ex);
}
}
Run Code Online (Sandbox Code Playgroud)
LoginForm.cs
private void checkUser(string username, string password)
{
using (Services.conn)
{
Services.conn.Open();
Services.DB_Select("..a short select statement..");
Services.conn.Close();
}
Run Code Online (Sandbox Code Playgroud)
我想这就是我们所需要的.我缩短了我的代码以专注于问题.
我创建了Services.cs以获得从所有表单访问数据库的全局方式,而无需复制和粘贴连接信息.现在,当我到达我的LoginForm.cs时,它会抛出错误"连接必须有效并打开".我已经调试了我的代码.它一直都是关闭的.即使通过conn.Open()它也会保持关闭状态.为什么?
另一个尝试:我也试着将conn.Open()和conn.Close()内部Services.DB_Select(..)的开头和结尾.这里也是错误的.
我不得不说:代码之前有效,我使用了相同的连接字符串.所以字符串本身肯定是有效的.
我感谢这里给予的任何帮助!
问题是您不存储从工厂属性返回的连接.但是不要像方法一样使用属性.而是以这种方式使用它:
using (var con = Services.conn)
{
Services.conn.Open();
Services.DB_Select("..a short select statement..", con ));
//Services.conn.Close(); unnecessary with using
}
Run Code Online (Sandbox Code Playgroud)
因此,在从属性返回的使用中使用相同的连接(或者在使用中更好地创建)并将其传递给使用它的方法.顺便说一句,使用属性作为工厂方法不是最佳实践.
但在我看来,创建使用它的连接要好得多,最好的地方就在using声明中.并将con属性扔到垃圾桶,它是毫无意义的,是一个令人讨厌的错误的来源.
public static void DB_Select(string s, params List<string>[] lists)
{
try
{
using(var conn = new MySqlConnection(Services.ServerConnection))
{
conn.Open();
MySqlCommand cmd = conn.CreateCommand();
cmd.CommandText = s;
using( var sqlreader = cmd.ExecuteReader())
while (sqlreader.Read())
{
if (sqlreader[0].ToString().Length > 0)
{
for (int i = 0; i < lists.Count(); i++)
{
lists[i].Add(sqlreader[i].ToString());
}
}
else
{
foreach (List<string> save in lists)
{
save.Add("/");
}
}
} // unnecessary to close the connection
} // or the reader with the using-stetement
}
catch (Exception ex)
{
MessageBox.Show("Error while selecting data from database!\nDetails: " + ex);
}
}
Run Code Online (Sandbox Code Playgroud)