MySqlCommand.ExecuteNonQuery fails - c#

I am trying to execute an INSERT query in a mysql DB, but it doesn't happen anything except that the code executions stops and nothing gets inserted.
Here is the code (the connection is made at another point and is working):
query = string.Format("INSERT INTO users (username, settings) VALUES('{0}', '{1}')", userName, sw.ToString());
myCommand = new MySqlCommand();
myCommand.CommandText = query;
myCommand.Connection = con;
myCommand.ExecuteNonQuery();
If I step the code, it stops after executenonquery, so obvisously something is wrong there. God I hate that it doesn't throw an error at me :(

Have you checked the connection is actually open and tried executing the method by assigning the result to an int in a try catch block.
int result;
try
{
if (conn.State != ConnectionState.Open)
conn.Open();
result = Convert.ToInt32(dbComm.ExecuteNonQuery());
}
catch (Exception ex)
{
logger.Error(ex);
}
finally
{
if (conn.State != ConnectionState.Closed)
conn.Close();
}

Related

Running the same query causing error the second time

I have a Data-table with all the mandatory fields which is required by select query in it. Now i am fetching data from 1st row of the data-table and running a select query (as given below). For the first time its working fine.
Now I am taking the 2nd row and giving all the mandatory fields (as i did for the first) and running the select query its giving error "insufficient permissions". When i am running both the select query (which are actually same but with different parameter) manually in Oracle SQL Developer its working fine.
Query1: select cloumnname1 from table where columnname2='valueA' and columnname3= 'VALUEB'
Query2: select cloumnname1 from table where columnname2='valueA' and columnname3= 'VALUEB'
To fetch data from database
public OracleDataReader ExecuteReader(string SelectQuery, string conString)
{
try
{
OpenDbConnection(conString);
OracleCommand cmd = new OracleCommand();
cmd.Connection = con;
cmd.CommandText = SelectQuery;
cmd.CommandType = System.Data.CommandType.Text;
OracleDataReader ora_dataReader = cmd.ExecuteReader();
return ora_dataReader;
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
}
EDIT:
Forgot to mention that i am calling this funtion in another function as given below
public DataTable GetDataFromDB(string SelectQuery, string conString)
{
try
{
DataTable dt = new DataTable();
dt.Load(ExecuteReader(SelectQuery,conString));
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
CloseDbConnection();
}
}
You need to open and close the connection after each query execution.
And also return the OracleDataReader after you have closed the connection or else it would lead to memory leak. If you return the OracleDataReader before you close connection, you would get the same error.
Try something like this:
public OracleDataReader ExecuteReader(string SelectQuery, string conString)
{
try
{
OpenDbConnection(conString);
OracleCommand cmd = new OracleCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = SelectQuery;
cmd.CommandType = System.Data.CommandType.Text;
OracleDataReader ora_dataReader = cmd.ExecuteReader();
}
catch (Exception ex)
{
Logging.LogMessage(Logging.LogLevel.Error, 0, "DAL", this.GetType().Name, ex.Message + " : " + ex.StackTrace);
throw ex;
}
finally
{
con.close();
con.Dispose();
}
return ora_dataReader;
}
More info in this reference: https://msdn.microsoft.com/en-us/library/system.data.oracleclient.oracledatareader(v=vs.110).aspx
You need to close the database connection and open it again before firing up your second query.
something like:
SqlConnection.Open();
And
SqlConnection.Close();
You need to ensure you're closing both the Connection and DataReader objects.
Try using the CommandBehavior argument in ExecuteReader, as it will close the connection automatically once you close the DataReader.
cmd.ExecuteReader(CommandBehavior.CloseConnection)

BeginTransaction() on sqltransaction freezes, how to use try catch to solve it?

I'm using SqlTransaction transaction = connection.BeginTransaction() in my C# application to get data from SQLServer.
The problem I have when there is no connection to server (no internet connection), then my application just freezes and stops working, no exception, no error, just freezes.
I tried use try catch to catch error, but even then application just freezes, and the only option is to kill application. Can anyone help me to catch this error and istead of freezeing give me error - like Connection to server failed. Please check internet connection.
Here is my class code for connection:
public static class RequestID
{
// Methods
public static int GetID(string server, string database, string user, string pass)
{
int num = 0;
using (SqlConnection connection = new SqlConnection(string.Format("server={0};database={1};uid={2};pwd={3};Connect Timeout=900", new object[] { server, database, user, pass })))
{
SqlCommand command = new SqlCommand("SELECT Value_Int FROM Param WHERE code= 'counter'");
SqlCommand command2 = new SqlCommand("UPDATE Param SET Value_Int = Value_Int + 1 WHERE code= 'counter'");
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
try
{
using (SqlTransaction transaction = connection.BeginTransaction())
{
try
{
command.Connection = connection;
command.Transaction = transaction;
command2.Connection = connection;
command2.Transaction = transaction;
num = (int)command.ExecuteScalar();
command2.ExecuteNonQuery();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
finally
{
if (connection.State != ConnectionState.Closed)
{
connection.Close();
}
}
}
}
catch (Exception ex)
{
throw;
}
return num;
}
}
}
Problem is in line:
using (SqlTransaction transaction = connection.BeginTransaction())
Thanks in advance.
P.S. Application works just fine, the only problam so far then connection to internet lost. I wasn't able to find solution...
Your problem is because
connection.Open();
is outside of your try block so you will never hit the catch.
Move that inside your try block.

system.invalidoperationexception

I am trying to run this code
public Exception SetData(string Data , long NoOfColumnsAllowed)
{
try
{
con = new SqlCeConnection(conectionstring);
con.Open();
transaction = con.BeginTransaction();
com = new SqlCeCommand();
com.Transaction = transaction;
com.CommandText = "Select count(*) from [Copy]";
com.Connection = con;
sdr = com.ExecuteReader();
while (sdr.Read())
{
noOfColumns = sdr.GetInt32(0);
}
if (noOfColumns > NoOfColumnsAllowed)
{
long NoOfColumsToBeDeleted = noOfColumns - NoOfColumnsAllowed;
com.CommandText = "delete from [Copy] where Sno<=#sno";
com.Parameters.AddWithValue("#sno", NoOfColumsToBeDeleted);
com.ExecuteNonQuery();
}
com.CommandText = "Insert into [Copy] (Data) values (#data)";
com.Parameters.AddWithValue("#data", Data);
com.ExecuteNonQuery();
transaction.Commit();
con.Close();
return null;
}
catch (Exception ex)
{
try
{
transaction.Rollback();
}
catch (Exception)
{
}
con.Close();
return ex;
}
}
Exception Occur -
system.invalidoperationexception : The transaction can not be
committed if there is any opened cursor in the scope of this
transaction . Make sure all the data readers/ result sets are
explicitly closed before committing the change .
I am new with transaction and not able to find any valuable solution about opened cursor. Is there something wrong with code or i have to explicitly close the data reader if yes please tell me how ?
Just call sdr.Close(); right after the while loop since that's what error is complaining about.

Insert row into database from C# form

String ConString = #"DataSource=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BizContact.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(ConString);
try
{
cn.Open();
MessageBox.Show("connect");
}
catch (Exception)
{
MessageBox.Show("Did not connect");
}
SqlCommand cmd = new SqlCommand("insert tableNote values (#UserName,#Note)",cn);
cmd.Parameters.AddWithValue("#UserName", textBox1.Text);
cmd.Parameters.AddWithValue("#Note", textBox2.Text);
try
{
int res = cmd.ExecuteNonQuery();
if (res > 0)
{
MessageBox.Show("insert");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
cn.Close();
}
I am trying to add new row to the database. The above code is correct with no error and it display the try statement but does not insert row into the database. Any idea to solve it.
try full T-SQL statement
"INSERT INTO table_name (userColumn, noteColumn) VALUES (#UserName, #Note)"
also dispose SqlConnection via using state
using(SqlConnection cn = new SqlConnection(ConString))
{
//....
}
Your insert statement is wrong (missing into). Do either:
insert into tableNote select #UserName,#Note
or
insert into tableNote (column_name1, column_name2) values (#UserName,#Note)
Open up Sql Profiler and watch it execute the command, then try replaying that command into Sql Management Studio. More than likely, it'll show you that the query is ever so slightly malformed such that it happily does nothing successfully.

in a "using" block is a SqlConnection closed on return or exception?

First question:
Say I have
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string storedProc = "GetData";
SqlCommand command = new SqlCommand(storedProc, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#EmployeeID", employeeID));
return (byte[])command.ExecuteScalar();
}
Does the connection get closed? Because technically we never get to the last } as we return before it.
Second question:
This time I have:
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
int employeeID = findEmployeeID();
connection.Open();
SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#EmployeeID", employeeID));
command.CommandTimeout = 5;
command.ExecuteNonQuery();
}
}
catch (Exception) { /*Handle error*/ }
Now, say somewhere in the try we get an error and it gets caught. Does the connection still get closed? Because again, we skip the rest of the code in the try and go directly to the catch statement.
Am I thinking too linearly in how using works? ie Does Dispose() simply get called when we leave the using scope?
Yes
Yes.
Either way, when the using block is exited (either by successful completion or by error) it is closed.
Although I think it would be better to organize like this because it's a lot easier to see what is going to happen, even for the new maintenance programmer who will support it later:
using (SqlConnection connection = new SqlConnection(connectionString))
{
int employeeID = findEmployeeID();
try
{
connection.Open();
SqlCommand command = new SqlCommand("UpdateEmployeeTable", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#EmployeeID", employeeID));
command.CommandTimeout = 5;
command.ExecuteNonQuery();
}
catch (Exception)
{
/*Handle error*/
}
}
Yes to both questions. The using statement gets compiled into a try/finally block
using (SqlConnection connection = new SqlConnection(connectionString))
{
}
is the same as
SqlConnection connection = null;
try
{
connection = new SqlConnection(connectionString);
}
finally
{
if(connection != null)
((IDisposable)connection).Dispose();
}
Edit: Fixing the cast to Disposable
http://msdn.microsoft.com/en-us/library/yh598w02.aspx
Here is my Template. Everything you need to select data from an SQL server. Connection is closed and disposed and errors in connection and execution are caught.
string connString = System.Configuration.ConfigurationManager.ConnectionStrings["CompanyServer"].ConnectionString;
string selectStatement = #"
SELECT TOP 1 Person
FROM CorporateOffice
WHERE HeadUpAss = 1 AND Title LIKE 'C-Level%'
ORDER BY IntelligenceQuotient DESC
";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand comm = new SqlCommand(selectStatement, conn))
{
try
{
conn.Open();
using (SqlDataReader dr = comm.ExecuteReader())
{
if (dr.HasRows)
{
while (dr.Read())
{
Console.WriteLine(dr["Person"].ToString());
}
}
else Console.WriteLine("No C-Level with Head Up Ass Found!? (Very Odd)");
}
}
catch (Exception e) { Console.WriteLine("Error: " + e.Message); }
if (conn.State == System.Data.ConnectionState.Open) conn.Close();
}
}
* Revised: 2015-11-09 *
As suggested by NickG; If too many braces are annoying you, format like this...
using (SqlConnection conn = new SqlConnection(connString))
using (SqlCommand comm = new SqlCommand(selectStatement, conn))
{
try
{
conn.Open();
using (SqlDataReader dr = comm.ExecuteReader())
if (dr.HasRows)
while (dr.Read()) Console.WriteLine(dr["Person"].ToString());
else Console.WriteLine("No C-Level with Head Up Ass Found!? (Very Odd)");
}
catch (Exception e) { Console.WriteLine("Error: " + e.Message); }
if (conn.State == System.Data.ConnectionState.Open) conn.Close();
}
Then again, if you work for EA or DayBreak games, you can just forgo any line-breaks as well because those are just for people who have to come back and look at your code later and who really cares? Am I right? I mean 1 line instead of 23 means I'm a better programmer, right?
using (SqlConnection conn = new SqlConnection(connString)) using (SqlCommand comm = new SqlCommand(selectStatement, conn)) { try { conn.Open(); using (SqlDataReader dr = comm.ExecuteReader()) if (dr.HasRows) while (dr.Read()) Console.WriteLine(dr["Person"].ToString()); else Console.WriteLine("No C-Level with Head Up Ass Found!? (Very Odd)"); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } if (conn.State == System.Data.ConnectionState.Open) conn.Close(); }
Phew... OK. I got that out of my system and am done amusing myself for a while. Carry on.
Dispose simply gets called when you leave the scope of using. The intention of "using" is to give developers a guaranteed way to make sure that resources get disposed.
From MSDN:
A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.
Using generates a try / finally around the object being allocated and calls Dispose() for you.
It saves you the hassle of manually creating the try / finally block and calling Dispose()
In your first example, the C# compiler will actually translate the using statement to the following:
SqlConnection connection = new SqlConnection(connectionString));
try
{
connection.Open();
string storedProc = "GetData";
SqlCommand command = new SqlCommand(storedProc, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#EmployeeID", employeeID));
return (byte[])command.ExecuteScalar();
}
finally
{
connection.Dispose();
}
Finally statements will always get called before a function returns and so the connection will be always closed/disposed.
So, in your second example the code will be compiled to the following:
try
{
try
{
connection.Open();
string storedProc = "GetData";
SqlCommand command = new SqlCommand(storedProc, connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#EmployeeID", employeeID));
return (byte[])command.ExecuteScalar();
}
finally
{
connection.Dispose();
}
}
catch (Exception)
{
}
The exception will be caught in the finally statement and the connection closed. The exception will not be seen by the outer catch clause.
I wrote two using statements inside a try/catch block and I could see the exception was being caught the same way if it's placed within the inner using statement just as ShaneLS example.
try
{
using (var con = new SqlConnection(#"Data Source=..."))
{
var cad = "INSERT INTO table VALUES (#r1,#r2,#r3)";
using (var insertCommand = new SqlCommand(cad, con))
{
insertCommand.Parameters.AddWithValue("#r1", atxt);
insertCommand.Parameters.AddWithValue("#r2", btxt);
insertCommand.Parameters.AddWithValue("#r3", ctxt);
con.Open();
insertCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message, "UsingTest", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
No matter where's the try/catch placed, the exception will be caught without issues.
Old thread but still relevant. I arrived here looking for a way out of having a using statement inside of a using statement. I am happy with this, notwithstanding any future insightful comments that change my mind. ;) Conversations here helped. Thanks. Simplified for readability -
public DataTable GetExchangeRates()
{
DataTable dt = new DataTable();
try
{
logger.LogInformation($"Log a message.");
string conStr = _config.GetConnectionString("conStr");
using (SqlCommand cmd = new SqlCommand("someProc", new SqlConnection(conStr)))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection.Open();
dt.Load(cmd.ExecuteReader());
}
return dt;
}
catch (Exception ex)
{
logger.LogError(ex, ex.Message);
}
}

Categories