I am working on asp.net frame work with 4.5 version and i am using mysql database for db transaction. I am using method which is common for DML operations such as insert,update and for select query also and I am using ExecuteNonQuery() method.
Here are my code sample
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("\nError in test: " + ex.StackTrace.ToString());
}
return ds;
}
And my sql is:
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;
In the above code select query is working but sometimes it is not giving result.
Here is my connection string:
Server=localhost;Database=abcdtest;Uid=root;Pwd=test;Connection Timeout=60000;CharSet=utf8;Convert Zero Datetime=true;
I also tried with ExecuteReader() please see below
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;
}