我正在使用Dao上的事務,特別是我第一次使用TransactionScope對象。但是,當我編譯,並開始在我的電腦我的程序我寫的方法給我這個錯誤:c#連接必須有效並且可以提交事務TransactionScope
連接必須是有效的,開放的,以提交事務
代碼:
public String insert(NewsVo news)
{
string query = "";
MySqlCommand cmd = null;
try
{
using (TransactionScope scope = new TransactionScope())
{
using (MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;Pwd=root;Database=Sql300365_1"))
{
conn.Open();
Int32 numTotali = Int32.Parse(getCount());
for (int i = numTotali - 1; i >= 0; i--)
{
query = "UPDATE " + table + " SET " + table + ".Priorita = ?PrioritaSet WHERE Priorita = ?Priorita";
cmd = new MySqlCommand(query, conn);
cmd.Parameters.Add("?Priorita", MySqlDbType.Int64).Value = i;
cmd.Parameters.Add("?PrioritaSet", MySqlDbType.Int64).Value = i + 1;
cmd.ExecuteReader();
}
query = "INSERT INTO " + table + " (Priorita, Data, Titolo) VALUES (0, ?Data, ?Titolo)";
cmd = new MySqlCommand(query, conn);
//cmd.Transaction = Transazione;
cmd.Parameters.Add("?Data", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_DATA).Value = news.Data;
cmd.Parameters.Add("?Titolo", MySqlDbType.VarChar, ConstDao.LENGHT_NEWS_TITOLO).Value = news.Titolo;
cmd.ExecuteReader();
news.IdNumber = cmd.LastInsertedId.ToString();
scope.Complete();
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
finally
{
cmd.Dispose();
}
return news.IdNumber;
}
請張貼問題在*英語* –
敢肯定你想'cmd.ExecuteNonQuery()的''而不是cmd.ExecuteReader()'...但我不知道你在問什麼所以它的盲目猜測。 – entropic
你並沒有配置你的閱讀器......'使用(cmd.ExecuteReader()){}'或'var reader = cmd.ExecuteReader(); reader.Close(); reader.Dispose();' –