ASP.NET 4.5中MySQL的ExecuteNonQuery()异常及查询无结果问题
问题描述
我基于ASP.NET Framework 4.5开发项目,使用MySQL数据库处理事务,编写了一个通用方法用于处理INSERT、UPDATE等DML操作及SELECT查询,最初采用ExecuteNonQuery()方法,但发现SELECT查询有时无法返回结果。
初始代码示例
public DataSet test(string sql, string Connectionstring) { DataSet ds = new DataSet(); try { string timeZone = '-05:00' using (MySqlConnection conn = new MySqlConnection(Connectionstring)) { try { conn.Open(); MySqlCommand cmd; if (!string.IsNullOrEmpty(timeZone)) { cmd = new MySqlCommand(); string zoneQuery = "SET SESSION time_zone = '" + timeZone + "';"; cmd.CommandText = zoneQuery; cmd.Connection = conn; cmd.CommandTimeout = connectiontimeout; cmd.ExecuteNonQuery(); cmd.Dispose(); } cmd = new MySqlCommand(); cmd.CommandText = sql; cmd.Connection = conn; cmd.CommandTimeout = connectiontimeout; cmd.ExecuteNonQuery(); MySqlDataAdapter ad = new MySqlDataAdapter(cmd); ad.Fill(ds); ad.Dispose(); cmd.Dispose(); conn.Close(); } finally { if (conn != null && conn.State != ConnectionState.Closed) { conn.Close(); } } } } catch (Exception ex) { objlogger.WritetoError("Error in test: " + ex.StackTrace.ToString()); } return ds; }
执行的SQL语句
select distinct(s.st),s.a,s.a1,s.a2,s.a3,s.a4,q.a5,l.a6,t.a7 from test1 as s join test2 as q on s.st = q.st join test3 as t on t.Uid = s.Uid join test4 as l on q.lt1 = l.lt1 where s.is1 = false && l.lt1 =8 && q.is_deleted = false && t.Is_Deleted = false && s.Is_Deleted = false && l.Is_Deleted = 0;
数据库连接字符串
Server=localhost;Database=abcdtest;Uid=root;Pwd=test;Connection Timeout=60000;CharSet=utf8;Convert Zero Datetime=true;
改用ExecuteReader()的尝试代码
public DataSet test(string sql, string Connectionstring) { DataSet ds = new DataSet(); try { string timeZone = '-04:00'; int connectiontimeout = 60000; using (MySqlConnection conn = new MySqlConnection(Connectionstring)) { try { conn.Open(); MySqlCommand cmd; MySqlDataReader myReader; if (!string.IsNullOrEmpty(timeZone)) { cmd = new MySqlCommand(); string zoneQuery = "SET SESSION time_zone = '" + timeZone + "';"; cmd.CommandText = zoneQuery; cmd.Connection = conn; cmd.CommandTimeout = connectiontimeout; myReader = cmd.ExecuteReader(); myReader.Close(); cmd.Dispose(); } MySqlDataAdapter adapter = new MySqlDataAdapter(); adapter.SelectCommand = new MySqlCommand(sql, conn); adapter.Fill(ds); conn.Close(); } finally { if (conn != null && conn.State != ConnectionState.Closed) { conn.Close(); } } } } catch (Exception ex) { objlogger.WritetoError("Error in test : " + ex.Message); } return ds; }
内容的提问来源于stack exchange,提问作者santosh
相关产品推荐
相关产品推荐

