我正在使用与多线程 sdk 交互的 c# 编写数据库类。我应该只使用一个连接(不用说!)但是,我总是收到有关connection 和 datareaders的错误。Anly 帮助表示赞赏。
这是我的代码的结构
static class Db
{
static MySqlConnection conn = new MySqlConnection(connectionString);
private static void Connect()
{
if (conn.State == ConnectionState.Closed)
conn.Open();
}
private static void DisConnect()
{
if (conn.State == ConnectionState.Open)
conn.Close();
}
static int Insert()
{
Connect();
MySqlCommand cmd = new MySqlCommand(sql, conn);
cmd.ExecuteNonQuery();
return Convert.ToInt32(cmd.LastInsertedId);
DisConnect();
}
public static DataTable select(string sql) //Especially fails here
{
Connect();
MySqlCommand cmd = new MySqlCommand(sql, conn);
using (MySqlDataReader read = cmd.ExecuteReader())
{
if (read.HasRows){ Some Code... }
}
DisConnect();
}
}