Connection must be valid and open. Error on MySql 5.2 - c#

I have this error at the call af stored procedure... Why?
public void InsertVideo()
{
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["AxWaveConnection"].ToString());
MySqlCommand cmd = new MySqlCommand("InsertVideo", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new MySqlParameter("in_youtubevideoid", VideoId));
cmd.Parameters.Add(new MySqlParameter("in_title", Title));
cmd.Parameters.Add(new MySqlParameter("in_rating", ViewCount));
cmd.Parameters.Add(new MySqlParameter("in_viewcount", Rating));
cmd.ExecuteNonQuery();
}

because you forget to OPEN the connection, before calling ExecuteNonQuery, call conn.Open() first,
conn.Open();
cmd.ExecuteNonQuery();

Your complete solution
public void InsertVideo()
{
MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["AxWaveConnection"].ToString());
MySqlCommand cmd = new MySqlCommand("InsertVideo", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open()
cmd.Parameters.Add(new MySqlParameter("in_youtubevideoid", VideoId));
cmd.Parameters.Add(new MySqlParameter("in_title", Title));
cmd.Parameters.Add(new MySqlParameter("in_rating", ViewCount));
cmd.Parameters.Add(new MySqlParameter("in_viewcount", Rating));
cmd.ExecuteNonQuery();
}

Related

oracle function always return null

I'm using the flowing code to call the oracle function with the return value,
but it returns null always
OracleCommand cmd = new OracleCommand();
using (OracleConnection cnn = new OracleConnection("Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=321352427544)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=test)));User ID=abc;Password=123;"))
{
cmd.Connection = cnn;
cmd.CommandText = "GetEmp";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("P_EMP_ID", OracleDbType.Int32).Value = 4241;
cmd.Parameters.Add(new OracleParameter("return_value", OracleDbType.Int32)).Direction = ParameterDirection.ReturnValue;
cnn.Open();
cmd.ExecuteNonQuery();
string Count = (string)cmd.Parameters["return_value"].Value;
cnn.Close();
}
the problem was solved in two ways by
add cmd.BindByName = true;
add the return parameter in the first: cmd.Parameters.Add(new OracleParameter("return_value", OracleDbType.Int32)).Direction = ParameterDirection.ReturnValue;

Nunit Testcase on Select and Update queries

I have written testcases for Database connection and select and update records.
Select Testcase -
using (SqlConnection cnn = new SqlConnection(connection))
{
cnn.Open();
cmd = new SqlCommand("AccessionDetails", cnn);
cmd.Parameters.Add(new SqlParameter("#CURRENTTIME", now));
cmd.Parameters.Add(new SqlParameter("#TIMEINTERVAL", Int32.Parse(ConfigurationManager.AppSettings["interval"])));
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(dt);
Assert.IsTrue(dt.Rows.Count > 0);
}
Update Testcase -
using (SqlConnection cnn = new SqlConnection(connection))
{
cnn.Open();
cmd = new SqlCommand("AccessionDetails", cnn);
cmd.Parameters.Add(new SqlParameter("#CURRENTTIME", now));
cmd.Parameters.Add(new SqlParameter("#TIMEINTERVAL", Int32.Parse(ConfigurationManager.AppSettings["interval"])));
cmd.CommandType = CommandType.StoredProcedure;
da.SelectCommand = cmd;
da.Fill(dt);
cmd = new SqlCommand("AccessionUpdate", cnn);
cmd.Parameters.Add(new SqlParameter("#ACCESSIONID", dt.Rows[1]["AccessionID"].ToString()));
cmd.CommandType = CommandType.StoredProcedure;
int affectedRows = cmd.ExecuteNonQuery();
Assert.IsTrue(dt.Rows.Count > 0);
}
I am using the same code where i implemented in the actual project code.
My select and update queries returns large set of values dynamically . So i cant not take single value and test it out in each Iteration.
My task is to Mock the above queries. Please help me in implementing the mocks.

C# No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type

Please Help!I got this err once i viewed in browser !! :
No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.
--- Not Able to execute --
=========================================
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
conn.ConnectionString = ConfigurationManager.ConnectionStrings[1].ToString();
cmd.Connection = conn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "ManageMember";
cmd.Parameters.AddWithValue("#check", "a");
cmd.Parameters.AddWithValue("#username", UserNameTxt.Text);
cmd.Parameters.AddWithValue("#password", PasswordTxt.Text);
cmd.Parameters.AddWithValue("#name", FullNameTxt.Text);
cmd.Parameters.AddWithValue("#email", EmailTxt.Text);
cmd.Parameters.AddWithValue("#phone", PhoneTxt.Text);
cmd.Parameters.AddWithValue("#company", CompanyTxt);
cmd.Parameters.AddWithValue("#gender", RdList.SelectedValue);
cmd.Parameters.AddWithValue("#BirthDate", BirthdateTxt.Text);
cmd.Parameters.AddWithValue("#question", Quastxt.Text);
cmd.Parameters.AddWithValue("#answer", AnswTxt.Text);
conn.Open();
cmd.ExecuteNonQuery();
lblMsg.Text = "User Added Successfully";
conn.Close();
Change
cmd.Parameters.AddWithValue("#company", CompanyTxt);
To
cmd.Parameters.AddWithValue("#company", CompanyTxt.Text);
Then smack yourself in the forehead.

Running Oracle Package: ORA-06550 || ORA-06502

When I try to run a package on our oracle database from Oracle's .net provider, or the Microsoft oracle provider, it gives me the following error:
{"ORA-06550: line 1, column 7:\nPLS-00221: 'BEGIN_TRANSACTION' is not a procedure or is undefined\nORA-06550: line 1, column 7:\nPL/SQL: Statement ignored"}
Here is my C# code:
OracleConnection cn = new OracleConnection(connectionString);
OracleCommand cmd = new OracleCommand();
cmd.Connection = cn;
cmd.CommandText = "DOTNET.SYSTEM_CRUD.BEGIN_TRANSACTION";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("p_user_id", OracleDbType.Decimal, ParameterDirection.Input).Value = 4720;
cmd.Parameters.Add("p_commt", OracleDbType.Varchar2, ParameterDirection.Input).Value = "TEST";
//cmd.Parameters.Add("return_value", OracleDbType.Decimal).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
Here is my package definition:
Function Begin_Transaction ( p_user_id IN NUMBER,
p_commt IN VARCHAR2
)
RETURN Number;
When I uncomment the third parameter that I've added, I get a different error:
{"ORA-06502: PL/SQL: numeric or value error: character to number conversion error\nORA-06512: at line 1"}
Try following code:
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = cn;
cmd.CommandText = "DOTNET.SYSTEM_CRUD.BEGIN_TRANSACTION";
cmd.CommandType = CommandType.StoredProcedure;
cmd.BindByName = true;
cmd.Parameters.Add(new OracleParameter("p_user_id", OracleDbType.Decimal, 4720, ParameterDirection.Input));
cmd.Parameters.Add(new OracleParameter("p_commt", OracleDbType.Varchar2, "TEST", ParameterDirection.Input));
cmd.ExecuteNonQuery();
}
Comment:
Don't forgive wrap disposable objects in using construction.
I removed the username from the package definition, and also uncommented my add parameter for the return value.
using (OracleConnection cn = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand())
{
cmd.Connection = cn;
cmd.CommandText = "SYSTEM_CRUD.BEGIN_TRANSACTION";
cmd.CommandType = CommandType.StoredProcedure;
cmd.BindByName = true;
cmd.Parameters.Add("p_user_id", OracleDbType.Decimal, ParameterDirection.Input).Value = 4720;
cmd.Parameters.Add("p_commt", OracleDbType.Varchar2, ParameterDirection.Input).Value = "TEST";
cmd.Parameters.Add("return_value", OracleDbType.Decimal).Direction = ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();

Using Block with Stored Procedures

i am trying to get used to working with "using" blocks in C#, but i'm having a hard time understanding when i should be using them.
here is an example.
my original code, without the using block:
SqlConnection conn = new SqlConnection(cCon.getConn());
SqlCommand cmd = new SqlCommand("sp_SaveSomething", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#x", xxx));
cmd.Parameters.Add(new SqlParameter("#ORG", ORG));
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{ }
finally
{
conn.Close();
}
but should i really be doing this? or should i be using(SqlConnection conn = new SqlConnection(cCon.getConn())) ? please help me understand this. is the way i'm originally doing it so wrong?
SqlConnection conn = new SqlConnection(cCon.getConn());
using( SqlCommand cmd = new SqlCommand("sp_SaveSomething", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#x", xxx));
cmd.Parameters.Add(new SqlParameter("#ORG", ORG));
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{ }
finally
{
conn.Close();
}
}
but i'm having a hard time understanding when i should be using them.
It's easy. Everytime you are dealing with a class that implements the IDisposable interface you should use them. Just like this:
using (SqlConnection conn = new SqlConnection(cCon.getConn()))
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "sp_SaveSomething";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#x", xxx));
cmd.Parameters.Add(new SqlParameter("#ORG", ORG));
cmd.ExecuteNonQuery();
}
and if you wanna handle some exceptions you could wrap the code you wanna handle in a try/catch statement:
try
{
using (SqlConnection conn = new SqlConnection(cCon.getConn()))
using (SqlCommand cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "sp_SaveSomething";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#x", xxx));
cmd.Parameters.Add(new SqlParameter("#ORG", ORG));
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
// do something here with the exception, don't just consume it,
// otherwise it's meaningless to catch it
}
As you can see all IDisposable resources (SqlConnection and SqlCommand in this code snippet) are now properly wrapped in using statements which guarantees that they will be properly disposed even if an exception is thrown. As a consequence you no longer need to be using a finally statement and explicitly doing this.
Also remember that ADO.NET uses a connection pool meaning that when you are calling the .Open() method on a SqlConnection you are not opening a physical connection to the database. You are simply drawing one from the pool. And when you call the .Close (or .Dispose) method you are not closing the connection. You are simply returning it to the connection pool so that it can be reused.
You wouldn't have to close the connection if you put it into using blocks. Using blocks are used for objects that implement IDisposable. IDisposable allows an object to clear unmanaged resources before being collected by the GC. This frees up memory and allows the GC to collect that object.
A using block is just a try/finally clause with automatic closing and disposing of disposable objects. Adding an internal try/catch serves only if you plan to handle in some way the exception thrown. In your example you do nothing in the catch block, so it is unnecessary.
Both the SqlCommand and SqlConnection are disposable so your code should be changed to
using(SqlConnection conn = new SqlConnection(cCon.getConn())
using( SqlCommand cmd = new SqlCommand("sp_SaveSomething", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#x", xxx));
cmd.Parameters.Add(new SqlParameter("#ORG", ORG));
conn.Open();
cmd.ExecuteNonQuery();
}
You should have a couple of using blocks here, actually, since SqlConnection and SqlCommand both implement IDisposable. And the using also takes care of closing the connection at the end, so the explicit conn.Close(); becomes unnecessary.
using (SqlConnection conn = new SqlConnection(cCon.getConn()))
using (SqlCommand cmd = new SqlCommand("sp_SaveSomething", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#x", xxx));
cmd.Parameters.Add(new SqlParameter("#ORG", ORG));
try
{
conn.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
// Log error, etc.
}
}
It will go this way:
using (SqlConnection conn = new SqlConnection(cCon.getConn()))
{
using (SqlCommand cmd = new SqlCommand("sp_SaveSomething", conn))
{
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#x", xxx));
cmd.Parameters.Add(new SqlParameter("#ORG", ORG));
cmd.ExecuteNonQuery();
}
}
As SqlConnection and SqlCommand implements the IDisposable interface, the using block will deal with the Close and Dispose methods.

Categories

Resources