Somehow MySQL suddenly cant execute queries after this is ran - c#

public void saveImage(byte[] image, int patient_id, MySqlConnection con)
{
string sql = "select * from patient where id ="+patient_id;
DataSet ds = new DataSet("patient");
MySqlDataAdapter dAdapter = new MySqlDataAdapter(sql, con);
MySqlCommandBuilder builder = new MySqlCommandBuilder(dAdapter);
dAdapter.Fill(ds, "patient2");
try
{
ds.Tables["patient2"].Rows[0]["picture"] = image;
dAdapter.Update(ds, "patient2");
// ds.Tables["patient2"].Rows[0].AcceptChanges();
con.Close();
con.Open();
}
catch (Exception exs)
{
Console.WriteLine(exs.Message);
}
}
How could i fix this error... after this is executed none of the following queries will work after that... what happened? i already tried commenting the "con.close" and "con.open" either way still,...

I suspect this happens because you close the connection, then reopen it. You're not supposed to reopen a closed connection... actually I'm surprised it doesn't throw an InvalidOperationException. And anyway, if your method receives an open connection as a parameter, it shouldn't close it. The code that opens the connection is responsible for closing it.

Related

c# there is already an open datareader associated with this command which must be closed first

I want to search data from another SQL Server table (Stocks_Item) to this form (IC) dataGridView1, I can view that data (from Stocks_Item) in this dataGridView1 but I couldn't search. Please help me.
Here is my code:
private void button5_Click(object sender, EventArgs e)
{
conn.Close();
try
{
conn.Open();
SqlCommand selectCommand = new SqlCommand("Select * from Stocks_Item where Stock_No = #Stocks_no", conn);
selectCommand.Parameters.Add(new SqlParameter("Stocks_no", txtsearch_stock_no.Text.ToString()));
SqlDataReader reader = selectCommand.ExecuteReader();
bool rowFound = reader.HasRows;
SqlDataAdapter data = new SqlDataAdapter("Select * from Stocks_Item", conn);
DataTable dt = new DataTable();
data.Fill(dt);
dataGridView1.DataSource = dt;
/* SqlDataAdapter sda;
DataTable dt1;
sda = new SqlDataAdapter("select * FROM colombo_branch ",conn);
dt1 = new DataTable();
sda.Fill(dt1);
dataGridView.DataSource = dt1;*/
MessageBox.Show("Search Found", "Form", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
conn.Close();
}
There are many flaws in your code, but the one that is specifically causing your error is because you are not properly closing the SqlDataReader here:
SqlDataReader reader = selectCommand.ExecuteReader();
bool rowFound = reader.HasRows;
As a result, the following line, which also attempts to open a data reader internally throws the exception:
data.Fill(dt);
Normally, you want to use a SqlDataReader inside a using block, something like:
bool rowFound;
using(SqlDataReader reader = selectCommand.ExecuteReader())
{
rowFound = reader.HasRows;
}
... to ensure proper and timely disposal. But in this case, I fail to see the point of that block of code anyways. So why not just remove it altogether?
Additional comments:
Avoid global connections. The fact that the method begins by closing the connection is not a good sign.
Always use using blocks around your SqlConnection, SqlCommand, SqlDataReader, SqlDataAdapter, etc... instances to make sure you don't run into these types of errors or leak resources.
I believe that SqlDataAdapter opens/closes a connection for you. Since you're doing that earlier in your code and using a reader against it, that would be the cause. You could use either the reader or the adapter, but typically wouldn't want to mix them in one connection without properly closing/disposing.
FYI, the MSDN SqlDataAdapter code example utilizes this auto open/close behavior of SqlDataAdapter

While in the Front End, how do you retrieve a DataSet returned by a WebMethod?

Within the Web Service, I am returning a DataSet using a WebMethod. However, I need to access that DataSet in the FrontEnd. How do I do this?
WebMethod:
[WebMethod]
public DataSet customerInformation(string orderNo)
{
try
{
SqlConnection myConnection = new SqlConnection(ConfigHelper.GetConnection());
myConnection.Open();
SqlDataAdapter adapter = new SqlDataAdapter("listTheCustomerNumber", myConnection);
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
SqlParameter parametersGroup = new SqlParameter("#orderNo", SqlDbType.VarChar, 10);
parametersGroup.Value = orderNo;
adapter.SelectCommand.Parameters.Add(parametersGroup);
// Create and Fill the DataSet
DataSet myDataSet = new DataSet();
adapter.SelectCommand.CommandTimeout = 240;
adapter.Fill(myDataSet);
myConnection.Close();
return myDataSet;
}
catch (Exception excep)
{
throw new System.FormatException("Error reading DataBase!", excep);
}
}
FE:
Step 1: Create event method for handling button click.
Step 2: Proxy call.
Step 3: I got nothing.
Never mind! Went brain-dead and forgot to update the WS within the Web References folder.
You may receive an error when you try it at first, so just run the program, copy the link into another browser, then close the window you originally emulated your code with.
After that just right-click the WS and select Update, and you should be good to go!

Already an open DataReader associated with this Connection

I use the code below to get data from mySql in C#. When I do that I get the error mentioned below the code. I found some question about the subject but they used DataReader, and I'm not.
MySqlConnection sq = new MySqlConnection("...");
sq.Open();
MySqlCommand sc = new MySqlCommand("select * from users", sq);
DataSet ds = new DataSet();
MySqlDataAdapter da = new MySqlDataAdapter(sc);
da.Fill(ds);
sq.Close();
My Error:
There is already an open DataReader associated with this Connection
which must be closed first.
in your connection string just add "MultipleActiveResultSets=True;"
I don't know if this fixes your issue, however...
Use the using statament for your connection, the command and the dataadapter. This disposes all objects that implement IDisposable and also closes the connection:
using(var sq = new MySqlConnection("..."))
using(var sc = new MySqlCommand("select * from users", sq))
using(var da = new MySqlDataAdapter(sc))
{
DataSet ds = new DataSet();
da.Fill(ds);
// you don't need to open/close the connection with a datadapter
} // but even without a dataadapter the using would have been closed the connection here
as the error said, you aren't closing every connection you open.
Probably because of and exception you get. you can use Tim's suggest:
using(var sq = new MySqlConnection("..."))
using(var sc = new MySqlCommand("select * from users", sq))
using(var da = new MySqlDataAdapter(sc))
or you can use try catch statement:
try
{
// Your code here
}
catch
{
// Whatever code you want here
}
finally
{
da.Close();
sc.Close();
sq.Close();
}
new MySqlCommand("select * from users", sq)
This implementation of the MySqlDataAdapter opens and closes a
MySqlConnection if it is not already open. This can be useful in a an
application that must call the DbDataAdapter.Fill method for two or
more MySqlDataAdapter objects. If the MySqlConnection is already open,
you must explicitly call MySqlConnection.Close or
MySqlConnection.Dispose to close it.
so, no need to open the connection, MySqlDataAdapter will open it when needed.
better to use using statements as other answers.

C# SQL connection problem

i am using VS.NET 2008 with MS SQL server 2005 to develop a window form application but everytime i got new error in connection or after conected,
in my current code the connection opened but doesnt work after that in transaction of queries. maybe i have problem while making new DB or new datasource also m not that satisfy how to get Connecting String
this is my code....
/////////
private void button1_Click(object sender, EventArgs e)
{
try
{
//setData();
string ConnectingString = #"Data Source=SERVER1\SQLEXPRESS;Initial Catalog=Alkawthar;Integrated Security=True;Pooling=False";
qry = "SELECT * FROM Table1";
//reader = db.select_data(qry);
ds1 = new DataSet();
conn = new SqlConnection(ConnectingString);
conn.Open();
MessageBox.Show("connection opened");
da.Fill(ds1,"Workers");
NavigateRecords();
MaxRows = ds1.Tables["Workers"].Rows.Count;
string sql = "SELECT * From tblWorkers";
da = new System.Data.SqlClient.SqlDataAdapter(sql, conn);
conn.Close();
MessageBox.Show("connection closed");
conn.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("exception");
MessageBox.Show(ex.Message);
}
}
/////////////////
Fill throws an exception also when i use reader it return null although there is data in DB
thanks
The most obvious problem here is that you access the SqlDataAdapter before initializing it. That will cause a null reference exception.
Try to move the line da = new SqlDataAdapter(...) to the line before you do the da.Fill(...).
Edit:
No, wait! I see that you do two queries and two fills in there. You need to initialize the SqlDataAdapter before doing the first fill. Then you should get rid of the null reference exception.
Edit again:
Also, as commented, you don't need call both the SqlConnection.Close and SqlConnection.Dispose methods. As long as you use the SqlDataAdapter you don't even need to do the SqlConnection.Open on the connection, for the Fill method will do all that for you. As long as the connection starts out being closed, the Fill method will close it again for you when it is done.
A few points of advice;
Like Turrau and Rune say, your stuff is in the wrong order. Open connection, Execute SQL - Get raw data, close connection. Then do your counting, etc.
Don't put message box or logging calls anywhere in between the connection opening and closing. This has burned me before, where the those calls can affect the SQL call because they fudge the exception details and make it difficult to trace. This is also applicable when using a SQL data reader.
Put the SQL stuff in a using block.
Try this...
string _connStr = #"Data Source=SERVER1\SQLEXPRESS;Initial Catalog=Alkawthar;Integrated Security=True;Pooling=False";
string _query = "SELECT * FROM Workers";
DataSet _ds = new DataSet();
try
{
using (SqlConnection _conn = new SqlConnection(_connStr))
{
SqlDataAdapter _da = new SqlDataAdapter(_query, _conn);
_conn.Open();
_da.Fill(_ds);
}
// insert null dataset or invalid return logic (too many tables, too few columns/rows, etc here.
if (_ds.Tables.Count == 1)
{ //There is a table, assign the name to it.
_ds.Tables[0].TableName = "tblWorkers";
}
//Then work with your tblWorkers
}
catch (Exception ex)
{
Console.Write("An error occurred: {0}", ex.Message);
}
Seems to me, that you use your DataAdapter before initialization. Do you get a NullReferenceException?
da.Fill(ds1,"Workers");
// ...
da = new System.Data.SqlClient.SqlDataAdapter(sql, conn);

Why is this class member leaving a SQL connection open?

Further to my recent questions, I've now closed most of the connections that our web application was leaving open. However, the connection created by the function below remains open. Can anyone identify why it is not closing?
public DataTable GetSubDepartment(int deptId)
{
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(Defaults.ConnStr))
{
SqlCommand cmd = new SqlCommand("proc_getDepartmentChild", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#dptParent", deptId));
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand = cmd;
da.Fill(dt);
}
return dt;
}
* EDIT *
Following #HenkHolterman's comment:
I'm using SQL Server Management Studio Activity log to view the open connections. This one is listed as sleeping. SO what you say makes sense. Is there any way I can tell that this is a pooled connection rather than an open one?
Most probably because it went back to the connection pool.
Call
SqlConnection.ClearAllPools();
to clear the pool, then it should disappear. This could sometimes be useful, but is usually not needed.
I would assume that it's hanging in the connectionpool

Categories

Resources