C# mysql one return last_insert_id - c#

I am trying to create a method in which I can exequte mysql UPDATE, DELETE or INSERT query. The method must work when with an INSERT I ask or do not ask the last_insert_id(). Below is the code that I have at the moment:
public int executeUID(MySqlCommand msCommand)
{
try
{
this.Open();
msCommand.Connection = this.msCon;
return int.Parse(msCommand.ExecuteScalar().ToString());
}
catch (MySqlException ex)
{
throw ex;
}
finally
{
this.Close();
}
}
The problem with this is is that when I use an insert query that returns a last_insert_id() the method works greatly. But when the query doesn't return an last_insert_id() the method malfunctions. How can I get this method to work?

why not u use OUTPUT parametres, it will return the last inserted id. SqlParamet
and if you know when LastInsertID can generate, then you can pass one more parameter to method, to tell that it is retriving insertedID, based on that parameter you can do some thing like this .
public int executeUID(MySqlCommand msCommand, bool Mode) //Mode==true means insertandRetriveLastID, false means =dont retrive last insertedit
{
try
{
this.Open();
msCommand.Connection = this.msCon;
if(Mode) //for getting last inserted id
{
SqlParameter outParams= new SqlParameter("#ID", SqlDbType.Int);
outParams.Direction = ParameterDirection.Output;
msCommand.Parameters.Add(outParams)
msCommand.ExecuteNonQuery();
var outputValue = cmd.Parameters["#ID"].Value;
}
else //if no inserted id is not there
{
return msComand.ExecuteNonQuery(); // it will return No of Rows Affected.
}
}
catch (MySqlException ex)
{
throw ex;
}
finally
{
this.Close();
}
}
PS : you need to tune it some more for better efficiency, as i gave some basic ideas how we can do it with out parameter

Related

Parameter count does not match Parameter Value count after minor change

I changed the code from this
public override IDataReader getData(int pageId, string pageName)
{
try
{
return ((IDataReader)(SqlHelper.ExecuteReader(ConnectionStringConnectorPool, GetFullyQualifiedName("PageModuleGetAll"),pageId, pageName)));
}
catch (Exception ex)
{
ExceptionController.WriteExceptionToLog(string.Format("SqlDataProvider.cs/GetPageByIdAndName: pageId:{0}, pageName{1}", pageId, pageName), -2, ex);
return null;
}
}
To this
public override IDataReader getData(string sqlMethod, int pageId, string pageName)
{
try
{
return ((IDataReader)(SqlHelper.ExecuteReader(ConnectionStringConnectorPool, GetFullyQualifiedName(sqlMethod),pageId, pageName)));
}
catch (Exception ex)
{
ExceptionController.WriteExceptionToLog(string.Format("SqlDataProvider.cs/GetPageByIdAndName: pageId:{0}, pageName{1}", pageId, pageName), -2, ex);
return null;
}
}
Im calling the method like this
public List<PageModuleInfo> GetAllPageModules(int pageId, string paneName)
{
try
{
return Common.Utilities.CBO.FillCollection<PageModuleInfo>(BLL.Data.DataProvider.Instance().getData("PageModuleGetAll", pageId, paneName));
}
catch (Exception ex)
{
ExceptionController.WriteExceptionToLog(new Exception("PageModuleController.cs/GetAllPageModules:" + System.Environment.NewLine + ex));
return null;
}
}
And now im getting Parameter count does not match Parameter Value count error and im wondering why.
The error indicates that you are using a stored procedure, and have supplied more parameter values than there are parameters declared on the stored procedure.
So: check each of the 3 stored procedures, and double-check how many parameters each takes. If one of them does not take at least 2, that is the problem. In particular, also check for different versions of the same stored procedure; for example, there could be dbo.PageModuleGetAll and johndev.PageModuleGetAll - where johndev.PageModuleGetAll is the updated version with 2 parameters. But if your application is running in with different identity (integrated security, a dedicated sql account, etc) - then it will still be running dbo.PageModuleGetAll
Your method is an override of a base class method, so it's likely that the derived classes function signature does not match the base classes signature.
That would give you a 'Parameter Value count error' because the base classes number of parameters is less than the derived class.

How to check if ObjectResult<> contains a value

How do I check to see if the ObjectResult<> has a value or not? Right now it's returning values but will it throw an exception is there is nothing to return?
This is the section of code that I need to check so I do not have to depend on a try catch block
iProjInfo.ProjectLeafs = db.proc_GetProjectLeafs(projectID).ToList<IProjectLeafs>();
public static Task<IProjectInfo> GetProjectInfo(int projectID)
{
return Task.Run(() =>
{
using (var db = new StorefrontSystemEntities())
{
IProjectInfo iProjInfo = db.proc_GetProject_ForDrawings(projectID).Single<IProjectInfo>();
try
{
iProjInfo.ProjectLeafs = db.proc_GetProjectLeafs(projectID).ToList<IProjectLeafs>();
}
catch (Exception ex)
{
}
return iProjInfo;
};
});
}
As long as the stored procedure is getting executed and returning a result set; even if it is empty (no records returned by the stored procedure), you can be sure of an empty list being returned.

savechanges() not saving?

I have this C# code:
public object guardardinerohoy(float dinero,string comentario)
{
object dineromov1 = this.nuevodineromovimiento(dinero, variablesestaticas.usuarioglobal, DateTime.Now, null, claseenumeraciones.enumdineromovimiento.iniciosistema, comentario, DateTime .Now );
object resultado = "ok";
string abrirconexion = Conexion.conexion.abrirconexion();
if (dineromov1.GetType() != "".GetType() && abrirconexion == "ok")
try
{
Conexion.conexion.conect.AddTodineromovimiento((dineromovimiento)dineromov1);
Conexion.conexion.conect.SaveChanges();
return "ok";
}
catch (Exception ex)
{
resultado = ex.Message;
}
else
{
resultado = dineromov1.ToString() + abrirconexion;
return resultado;
}
}
I return "ok" if this saved successfully. Now when I checked if this was saved it was not. I do not understand why if it did not return an exception. This does not happen all the time. Sometimes it saves and sometime it does not.
I found this thread which says if it does not have exception, everything is ok.
Check if an insert or update was successful in Entity Framework
Entity Framework will throw an exception upon failure of Insert, Update or Delete.
Thus, you can assume with no exception that it's successful.

Error in returning value in asp.net

public bool ConnectToDB()
{
SqlConnection sqlConnect = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString());
try
{
sqlConnect.Open();
if (sqlConnect.State == ConnectionState.Open)
{
return true;
}
}
catch (SqlException ex)
{
// some code here...
}
finally
{
sqlConnect.Close();
}
}
when I run this code,it is giving an error
Error 'DataAccess.ConnectToDB()': not all code paths return a value
you have to put all return condition in function.
public bool ConnectToDB()
{
SqlConnection sqlConnect = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ToString());
try
{
sqlConnect.Open();
if (sqlConnect.State == ConnectionState.Open)
{
return true;
}else
return false;
}
catch (SqlException ex)
{
return false;
}
finally
{
sqlConnect.Close();
}
}
Your method signature says that you return a bool (public bool ConnectToDB()). However, you only return a bool when your connection is open.
I think you intend to return false otherwise. If so, return false from your catch clause.
catch (SqlException ex)
{
// some code here...
return false;
}
You will need to amend a return value outside the if condition as to what will happen if there was a exception before the 'return true' reaches or if the IF condition fails? You would need to have the return statement in the else part and in the catch block.
Consider in your code if an exception happens which gets handled in the catch but return true is never reached and the execution is now in catch and then moves to the finally block. So you would need to add return false in the catch part for this to compile.
When you have a return type all of your code paths i.e. try/catch blocks are supposed to return something. In this case, a false would be a appropriate value. However, if the catch blocks rethrows the exception it wont be required.
You need to add return true at the end of function, and add return false in exception block.
It seems superfluous that you're opening the connection to check if the database is open. In fact, one could argue that if the database connection is already open it will throw an exception. You do have exception handling involved but you can simply check the state without opening a connection:
public bool ConnectToDB() {
return sqlConnect.State == ConnectionState.Open;
}

try-catch blocks with the return type

If I have a method that returns something, like
public DataTable ReturnSomething()
{
try
{
//logic here
return ds.Tables[0];
}
catch (Exception e)
{
ErrorString=e.Message;
}
}
This produces compiler error, obviously because catch{} block does not return anything.
So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?
Store your return value in a temporary variable like this:
public DataTable ReturnSomething()
{
DataTable returnValue = null;
try
{
//logic here
returnValue = ds.Tables[0];
}
catch (Exception e)
{
ErrorString=e.Message;
}
return returnValue;
}
You should raise/throw the exception in your catch block and handle it in the calling method.
public void invokeFaultyCode()
{
try
{
DataTable dt = ReturnSomething();
}
catch(Exception e)
{
// Print the error message, cleanup, whatever
}
}
public DataTable ReturnSomething() throws Exception
{
try
{
//logic here
return ds.Tables[0];
}
catch (Exception e)
{
ErrorString=e.Message;
throw;
}
}
PS: Sorry for any syntax error, I'm a bit rusty on C#.
You should wrap the caller with a try catch... any exceptions that happen in the routine that is called will bubble out to the caller and you can catch them there.
Personally, I think it is overkill to have a try catch in this routine as you should have the caller handling the exception.
For my example, this would be coded as follows...
private void DoSomething() {
try {
DataTable dt = ReturnSomething();
}
catch (Exception ex) {
}
}
public DataTable ReturnSomething() {
DataTable dt = new DataTable();
// logic here
return dt;
}
The ErrorString variable looks suspiciously like an error code variable. Recommended practice is to use exceptions to pass error information directly, where necessary, rather than storing things off into error codes.
You are effectively doing the same thing with your ErrorString as you would be if you just let the exception be caught by the caller: removing the responsibility of responding to an error from the method itself. This is a good goal to have. But the use of an error string doesn't gain you anything over the use of an exception. In fact, you lose information this way. There are any number of types of errors that could occur, and many have special exceptions associated with them, with their own special properties to hold contextual info about the failure. By just storing off the message in a String, you're losing this information.
So unless your goal is specifically to hide the type of error that is occurring from the caller, you can only gain by letting the exception through.
Another thing to consider is whether this is truly an error scenario. If it is, it's very unlikely that your calling method is going to care at all what the return value is. In which case, you have nothing to worry about by just letting the exception go and not returning anything. If it's NOT really an error scenario, and the caller is just going to continue on and do something else, well, that's for the caller to decide, right? There's still not much benefit to obtain by returning an error string and a dummy DataTable or a null, over throwing the exception with all its contextual failure info.
If you are going to head the "don't throw an exception route" (which I am not necessarily reccomending), you could follow the TryParse approach MS uses.
Something like:
private string FillDataTable(out DataTable results)
{
try
{
results = new DataTable(); //something like this;
return String.Empty;
}
catch (Exception ex)
{
results = null;
return ex.Message;
}
}
It depends on you application. You can return null, an empty DataTable or whatever is suitable under circumstances.
i'd assume you can still set the message, then return null or whatever the c# equivalent is
public DataTable ReturnSomething(){
try {
//logic here
return ds.Tables[0];
} catch (Exception e) {
ErrorString=e.Message;
return null;
}
}
How about this :
public DataTable ReturnSomething(out string errorString)
{
errorString = string.Empty;
DataTable dt = new DataTable();
try
{
//logic here
dt = ds.Tables[0];
}
catch (Exception e)
{
errorString = e.Message;
}
return dt;
}
Since you are cacthing the exception (and not throwing it again) in your example, The outside code assumes everyting is okay and therefor you should return something useful.
If you need to catch the exception there and do somthing that's all fine, but if it's still an error case you should also throw it, or a different exception, perhaps with the one you just caught as InnerException.
I think your code is being run at a sufficiently high level of the call stack and it's blended with UI code. If this is really the case, you could return null in the catch block. However, if you are writing reusable code, you should refactor it so that it doesn't contain UI manipulation and handle the exception at a higher level in the call stack.
You can do it like the sample code below.
public DataTable ReturnSomething(out string OutputDesc)
{
try
{
//logic here
OutputDesc = string.Format("Your Successful Message Here...");
return ds.Tables[0];
}
catch (Exception e)
{
OutputDesc =e.Message;
return null;
}
}
Simple
public DataTable ReturnSomething()
{
try
{
//logic here
return ds.Tables[0];
}
catch (Exception e)
{
ErrorString=e.Message;
throw new Exception(e.Message);
}
}

Categories