ASP, The SqlParameter is already contained by another SqlParameterCollection - c#

I have a problem when executing a SQL Server stored procedure in my application. I've not had this problem before.
My data class is:
public static string conStr
{
get { return ConfigurationManager.ConnectionStrings["conn"].ConnectionString; }
}
public static string Provider
{
get { return ConfigurationManager.ConnectionStrings["conn"].ProviderName; } //Proveedor de DB
}
//DB PROVIDER FACTORY: Objetos de Conexion
public static System.Data.Common.DbProviderFactory dpf
{
get { return DbProviderFactories.GetFactory(Provider); }
}
private static int ejecutaNonQuery(string StoredProcedure, List<DbParameter> parametros)
{//execute nonquery retorna el numero de columnas afectadas en una dB
int Id = 0; //variable para saber cuantos elementos se modificaron despues del ejecutenonquery
try
{
using (DbConnection con = dpf.CreateConnection()) //al usar using la conexion se cerrara automaticamente
{
con.ConnectionString = conStr;
using (DbCommand cmd = dpf.CreateCommand())
{
cmd.Connection = con;
cmd.CommandText = StoredProcedure;
cmd.CommandType = CommandType.StoredProcedure;
foreach (DbParameter param in parametros)
cmd.Parameters.Add(param);
con.Open();
Id = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{ }
return Id;
}
This is the execution:
public int Lotes_Crear_Consolidado(string cliCodigo, string cajCodigo, int cajNumero,
int cajConNumero, string cajConCodigo,
string id1Desde, string id1Hasta,
string id2Desde, string id2Hasta,
string id3Desde, string id3Hasta,
string id4Desde, string id4Hasta,
string id5Desde, string id5Hasta,
string altaPor, string lotEstado,
DateTime fecEmiLot, DateTime fecCadLot)
{
List<DbParameter> paramLotesConsol = new List<DbParameter>();
DbParameter param1 = dpf.CreateParameter();
param1.DbType = DbType.String;
param1.Value = cliCodigo;
param1.ParameterName = "CLIENTE_CODIGO";
paramLotesConsol.Add(param1);
DbParameter param2 = dpf.CreateParameter();
param2.DbType = DbType.String;
param2.Value = cajCodigo;
param2.ParameterName = "CAJA_CODIGO";
paramLotesConsol.Add(param2);
DbParameter param3 = dpf.CreateParameter();
param3.DbType = DbType.Int16;
param3.Value = cajNumero;
param3.ParameterName = "CAJA_NUMERO";
paramLotesConsol.Add(param3);
DbParameter param4 = dpf.CreateParameter();
param4.DbType = DbType.Int16;
param4.Value = cajConNumero;
param4.ParameterName = "CAJA_CONTENIDO_NUMERO";
paramLotesConsol.Add(param4);
DbParameter param5 = dpf.CreateParameter();
param5.DbType = DbType.String;
param5.Value = cajConCodigo;
param5.ParameterName = "CAJA_CONTENIDO_CODIGO";
paramLotesConsol.Add(param5);
DbParameter param6 = dpf.CreateParameter();
param6.DbType = DbType.String;
param6.Value = id1Desde;
param6.ParameterName = "ID1_DESDE";
paramLotesConsol.Add(param6);
DbParameter param7 = dpf.CreateParameter();
param7.DbType = DbType.String;
param7.Value = id1Hasta;
param7.ParameterName = "ID1_HASTA";
paramLotesConsol.Add(param7);
DbParameter param8 = dpf.CreateParameter();
param8.DbType = DbType.String;
param8.Value = id2Desde;
param8.ParameterName = "ID2_DESDE";
paramLotesConsol.Add(param8);
DbParameter param9 = dpf.CreateParameter();
param9.DbType = DbType.String;
param9.Value = id2Hasta;
param9.ParameterName = "ID2_HASTA";
paramLotesConsol.Add(param9);
........
DbParameter param26 = dpf.CreateParameter();
param26.DbType = DbType.String;
param26.Value = altaPor;
param26.ParameterName = "ALTA_POR";
paramLotesConsol.Add(param26);
DbParameter param27 = dpf.CreateParameter();
param27.DbType = DbType.String;
param27.Value = lotEstado;
param27.ParameterName = "ESTADO";
paramLotesConsol.Add(param27);
DbParameter param28 = dpf.CreateParameter();
param28.DbType = DbType.Date;
param28.Value = fecEmiLot;
param28.ParameterName = "FECHA_EMISION_LOTE";
paramLotesConsol.Add(param28);
DbParameter param29 = dpf.CreateParameter();
param29.DbType = DbType.Date;
param29.Value = fecCadLot;
param29.ParameterName = "FECHA_CADUCID_LOTE";
paramLotesConsol.Add(param29);
return ejecutaNonQuery("LOTES_CREAR_CONSOLIDADO", paramLotesConsol);
}
Then I call it like this:
Caja_Contenido_BL loteBL = new Caja_Contenido_BL();
I must insert data from a gridview to my database, so I run on every row the stored procedure for inserting the data.
And the error I get is:
The SqlParameter is already contained by another SqlParameterCollection
Code:
protected void Lotes_Crear_Consolidado(object sender, EventArgs e)
{
string altaPor = User.Identity.Name.ToString().ToUpper();
foreach (GridViewRow grdCajUpd_Row in this.gvwLotConsol_Plant.Rows)
{
string cliCod = Convert.ToString(grdCajUpd_Row.Cells[0].Text);
string cajCod = Convert.ToString(grdCajUpd_Row.Cells[1].Text);
int cajNum = Convert.ToInt16(grdCajUpd_Row.Cells[2].Text);
int cajConNum = Convert.ToInt16(grdCajUpd_Row.Cells[3].Text);
string cajConCod = Convert.ToString(grdCajUpd_Row.Cells[4].Text);
string id1Desde = Convert.ToString(grdCajUpd_Row.Cells[5].Text);
string id1Hasta = Convert.ToString(grdCajUpd_Row.Cells[6].Text);
string id2Desde = Convert.ToString(grdCajUpd_Row.Cells[7].Text);
string id2Hasta = Convert.ToString(grdCajUpd_Row.Cells[8].Text);
string id3Desde = Convert.ToString(grdCajUpd_Row.Cells[9].Text);
string id3Hasta = Convert.ToString(grdCajUpd_Row.Cells[10].Text);
string id4Desde = Convert.ToString(grdCajUpd_Row.Cells[11].Text);
string id4Hasta = Convert.ToString(grdCajUpd_Row.Cells[12].Text);
string id5Desde = Convert.ToString(grdCajUpd_Row.Cells[13].Text);
string id5Hasta = Convert.ToString(grdCajUpd_Row.Cells[14].Text);
string id6Desde = Convert.ToString(grdCajUpd_Row.Cells[15].Text);
string id6Hasta = Convert.ToString(grdCajUpd_Row.Cells[16].Text);
string id7Desde = Convert.ToString(grdCajUpd_Row.Cells[17].Text);
string id7Hasta = Convert.ToString(grdCajUpd_Row.Cells[18].Text);
string id8Desde = Convert.ToString(grdCajUpd_Row.Cells[19].Text);
string id8Hasta = Convert.ToString(grdCajUpd_Row.Cells[20].Text);
string id9Desde = Convert.ToString(grdCajUpd_Row.Cells[21].Text);
string id9Hasta = Convert.ToString(grdCajUpd_Row.Cells[22].Text);
string id10Desde = Convert.ToString(grdCajUpd_Row.Cells[23].Text);
string id10Hasta = Convert.ToString(grdCajUpd_Row.Cells[24].Text);
string estado = Convert.ToString(grdCajUpd_Row.Cells[25].Text);
DateTime fecEmiLot = Convert.ToDateTime(grdCajUpd_Row.Cells[26].Text);
DateTime fecCadLot = Convert.ToDateTime(grdCajUpd_Row.Cells[27].Text);
loteBL.Lotes_Crear_Consolidado(cliCod, cajCod, cajNum, cajConNum, cajConCod,
id1Desde, id1Hasta, id2Desde, id2Hasta, id3Desde, id3Hasta, id4Desde, id4Hasta,
id5Desde, id5Hasta, id6Desde, id6Hasta, id7Desde, id7Hasta, id8Desde, id8Hasta,
id9Desde, id9Hasta, id10Desde, id10Hasta, altaPor, estado, fecEmiLot, fecCadLot);
}
Page.ClientScript.RegisterStartupScript(this.GetType(), "AlertScript", "alert('Lote(s) Creado(s)!');", true);
}
I clear command parameters with cmd.Parameters.Clear().
In SQL Server, I use the same name in SQL parameters for other stored procedures.
I don't know what the problem could be.
Please, if anyone can help me, I wold be grateful
Best regards

You can only use a SqlParameter once. Since you're passing SqlParameters into the method, I assume they are also used somewhere else?
If you wish to keep your call signature and want a quick fix, try this. Instead of
foreach (DbParameter param in parametros)
cmd.Parameters.Add(param);
Try
foreach (ICloneable param in parametros)
cmd.Parameters.Add(param.Clone() as SqlParameter);

If I recall correctly, you need to edit the post in order to delete it. To avoid this sort of issue, I would recommend creating a helper function like this:
private void AddParameter(DbProviderFactory dpf, List<DbParameter> params, DbType type, object value, string name)
{
DbParameter param = dpf.CreateParameter();
param.DbType = type;
param.Value = value;
param.ParameterName = name;
params.Add(param);
}
Then call it like this:
AddParameter(dpf, paramLotesConsol, DbType.String, cliCodigo, "CLIENTE_CODIGO");
AddParameter(dpf, paramLotesConsol, DbType.String, cajCodigo, "CAJA_CODIGO");
// etc.

Thanks guys for helping.
It was my mistake, I'm handling almost 30 parameters, one of them was duplicate.

Related

Using Placeholder TextBoxes- Error Message Procedure or function expects parameter which was not supplied

I have a function that I would want to use to check if a seal number exists in the database but whenever I add the parameters it is telling to supply parameter when the parameter is there. If it exists it should throw at an error message to user. Based on the fact that I'm using a placeholder textbox; I'm not sure if I'm going about it the right way as it is giving this error message Procedure or function 'PP_CountSeal' expects parameter '#seal2', which was not supplied
Stored Procedure
ALTER PROCEDURE [dbo].[PP_CountSeal]
-- Add the parameters for the stored procedure here
#seal1 nchar(15),
#seal2 nchar(15),
#seal3 nchar(15),
#seal4 nchar(15),
#seal5 nchar(15),
#seal6 nchar(15),
#seal7 nchar(15)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- nchar(10),erfering with SELECT statements.
--SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT seal1,seal2,seal3,seal4,seal5,seal6,seal7 From TWCL_OPERATIONS.dbo.PP_SealNumber
WHERE seal1 = #seal1 or seal1=#seal2 or seal1=#seal3 or seal1=#seal4 or seal1=#seal5 or seal1=#seal6 or seal1=#seal7
or seal2 = #seal1 or seal2=#seal2 or seal2=#seal3 or seal2=#seal4 or seal2=#seal5 or seal2=#seal6 or seal2=#seal7
or seal3 = #seal1 or seal3=#seal2 or seal3=#seal3 or seal3=#seal4 or seal3=#seal5 or seal3=#seal6 or seal3=#seal7
or seal4 = #seal1 or seal4=#seal2 or seal4=#seal3 or seal4=#seal4 or seal4=#seal5 or seal4=#seal6 or seal4=#seal7
or seal5 = #seal1 or seal5=#seal2 or seal5=#seal3 or seal5=#seal4 or seal5=#seal5 or seal5=#seal6 or seal5=#seal7
or seal6 = #seal1 or seal6=#seal2 or seal6=#seal3 or seal6=#seal4 or seal6=#seal5 or seal6=#seal6 or seal6=#seal7
or seal7 = #seal1 or seal7=#seal2 or seal7=#seal3 or seal7=#seal4 or seal7=#seal5 or seal7=#seal6 or seal7=#seal7
END
GO
//Check if Seal Number exists
private bool SealCheck()
{
bool R = true;
int a = 0;
SqlConnection con = new SqlConnection(connection);
con.Open();
foreach (Control cntrl in phSealNum.Controls)
{
SqlCommand C = new SqlCommand("PP_CountSeal", con);
C.CommandType = CommandType.StoredProcedure;
//Add Parameters
TextBox txt = (TextBox)cntrl;
string str = txt.Text.TrimEnd();
string seal = string.Format("#seal{0}", a);
C.Parameters.AddWithValue(seal, str);
R = Convert.ToBoolean(C.ExecuteScalar());
a++;
}
protected void Update_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(connection);
#region Seal Data
string previousseal1 = null;
string previousseal2 = null;
string previousseal3 = null;
string previousseal4 = null;
string previousseal5 = null;
string previousseal6 = null;
string previousseal7 = null;
bool X = SealCheck();
string name = HttpContext.Current.User.Identity.Name;
if (X == false)
{
SqlCommand command = new SqlCommand("PP_SealRecord", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#loadSheetNum", dispatchSheetNo);
SqlDataReader data = command.ExecuteReader();
if (data.Read())
{
previousseal1 = Convert.ToString(data["seal1"]);
previousseal2 = Convert.ToString(data["seal2"]);
previousseal3 = Convert.ToString(data["seal3"]);
previousseal4 = Convert.ToString(data["seal4"]);
previousseal5 = Convert.ToString(data["seal5"]);
previousseal6 = Convert.ToString(data["seal6"]);
previousseal7 = Convert.ToString(data["seal7"]);
EditSeal(dispatchSheetNo, previousseal1, previousseal2, previousseal3, previousseal4, previousseal5, previousseal6, previousseal7, name);
}
else
{
// INSERT STATEMENT
CreateSeal(loadsheet, CreatedBy);
}
}
else
{
lblError.Text = "Seal Number Exists";
}
con.Close();
#endregion
}
showData();
}
Your code:
foreach (Control cntrl in phSealNum.Controls)
{
SqlCommand C = new SqlCommand("PP_CountSeal", con);
C.CommandType = CommandType.StoredProcedure;
//Add Parameters
TextBox txt = (TextBox)cntrl;
string str = txt.Text.TrimEnd();
string seal = string.Format("#seal{0}", a);
C.Parameters.AddWithValue(seal, str);
R = Convert.ToBoolean(C.ExecuteScalar());
a++;
}
Your sp is asking for all parameters but you are iterating phSealNum.Controls collection, in the loop body you passing one parameter and executing sp and next missing parameter is #seal2 which is not passed causing error.
My code:
SqlCommand C = new SqlCommand("PP_CountSeal", con);
C.CommandType = CommandType.StoredProcedure;
foreach (Control cntrl in phSealNum.Controls)
{
//Add Parameters
TextBox txt = (TextBox)cntrl;
string str = txt.Text.TrimEnd();
string seal = string.Format("#seal{0}", a);
a++;
C.Parameters.AddWithValue(seal, str);
}
R = Convert.ToBoolean(C.ExecuteScalar());
Here I am adding all parameters in loop body and then executing query. hope it helps. Please let me know about the same.

ORA-01036: illegal variable name/number while updating gridview

I want to update a cell of the row in gridview. But I am getting error as
ORA-01036: illegal variable name/number
at cmd.ExecuteNonQuery()
Here is my code below:-
protected void SaveChanges(object sender, EventArgs e)
{
myConn.Open();
string excelData = Grid1ExcelData.Value;
string excelDeletedIds = Grid1ExcelDeletedIds.Value;
string[] rowSeparator = new string[] { "|*row*|" };
string[] cellSeparator = new string[] { "|*cell*|" };
string[] dataRows = excelData.Split(rowSeparator, StringSplitOptions.None);
for (int i = 0; i < dataRows.Length; i++)
{
string[] dataCells = dataRows[i].Split(cellSeparator, StringSplitOptions.None);
string mkey = dataCells[0];
string shipName = dataCells[1];
string shipCity = dataCells[2];
string shipAddress = dataCells[3];
string shipCountry = dataCells[4];
string orderDate = dataCells[5];
bool sent = dataCells[6] == "yes";
string insertUpdateQuery = "";
if (!string.IsNullOrEmpty(mkey))
{
insertUpdateQuery = "UPDATE B_Order_new SET ShipName = #ShipName, ShipCity = #ShipCity, ShipAddress = #ShipAddress, ShipCountry = #ShipCountry, OrderDate = #OrderDate, Sent = #Sent WHERE MKEY = #MKEY";
}
else
{
insertUpdateQuery = "INSERT INTO B_Order_new (ShipName, ShipCity, ShipAddress, ShipCountry, OrderDate, Sent) " +
"VALUES(#ShipName, #ShipCity, #ShipAddress, #ShipCountry, #OrderDate, #Sent)";
}
OracleCommand cmd = new OracleCommand(insertUpdateQuery, myConn);
var orderedOn = DateTime.ParseExact(orderDate, "dd/MM/yyyy", null);
cmd.Parameters.Add("#ShipName", OracleType.VarChar).Value = shipName;
cmd.Parameters.Add("#ShipCity", OracleType.VarChar).Value = shipCity;
cmd.Parameters.Add("#ShipAddress", OracleType.VarChar).Value = shipAddress;
cmd.Parameters.Add("#ShipCountry", OracleType.VarChar).Value = shipCountry;
cmd.Parameters.Add("#OrderDate", OracleType.DateTime).Value = orderedOn;
cmd.Parameters.Add("#Sent", OracleType.Char).Value = true;
if (!string.IsNullOrEmpty(mkey))
{
cmd.Parameters.Add("#MKEY", OracleType.Number).Value = mkey;
}
cmd.ExecuteNonQuery();
if (insertUpdateQuery != "")
{
Page.ClientScript.RegisterStartupScript(typeof(Page), "CloseScript", "alert('Data Updated succesfully');", true);
}
}
if (!string.IsNullOrEmpty(excelDeletedIds))
{
OracleCommand deleteComm = new OracleCommand("DELETE FROM Orders WHERE OrderID IN (" + excelDeletedIds + ")", myConn);
deleteComm.ExecuteNonQuery();
}
myConn.Close();
Grid1.DataBind();
}
The problem is that you are using the wrong bind variable syntax (looks like you're using SQL Server parameter binding syntax). Oracle's ADO.NET provider expects you to use a : prefix rather than a #.
So try something like this instead:
insertUpdateQuery = "UPDATE B_Order_new SET ShipName = :ShipName, ShipCity = :ShipCity, ...
And then when setting the values, you don't need to prefix it:
cmd.Parameters.Add("ShipName", OracleType.VarChar).Value = shipName;
cmd.Parameters.Add("ShipCity", OracleType.VarChar).Value = shipCity;
...
EDIT
Also, if you are binding the parameters by name, make sure you set the OracleCommand.BindByName property to true. Otherwise, the binding will be done positionally.

Procedure or function has too many arguments specified

Below is my stored procedure for insert:
CREATE PROCEDURE [dbo].[Insertaddress_Master]
(
#add_Zip nvarchar(20),
#add_FullAddress nvarchar(250),
#add_user_Id int,
#add_CreatedDate datetime,
#add_UpdatedDate datetime,
#add_DeletedDate datetime,
#add_IsDeleted bit,
#add_IsPrimary bit,
#add_cntm_Id int,
#add_alt_No nvarchar(20)
)
As
BEGIN
SET NOCOUNT ON
Insert Into [address_Master]
(
[add_Zip],
[add_FullAddress],
[add_user_Id],
[add_CreatedDate],
[add_UpdatedDate],
[add_DeletedDate],
[add_IsDeleted],
[add_IsPrimary],
[add_cntm_Id],
[add_alt_No]
)
Values
(
#add_Zip,
#add_FullAddress,
#add_user_Id,
#add_CreatedDate,
#add_UpdatedDate,
#add_DeletedDate,
#add_IsDeleted,
#add_IsPrimary,
#add_cntm_Id,
#add_alt_No
)
END
Below is code behind function:
protected void AddNew(object sender, EventArgs e)
{
try
{
address_MasterBM obj = new address_MasterBM();
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_Zip")).Text != "")
{
String add_Zipstr = ((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_Zip")).Text;
obj.add_Zip = add_Zipstr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_FullAddress")).Text != "")
{
String add_FullAddressstr = ((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_FullAddress")).Text;
obj.add_FullAddress = add_FullAddressstr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_user_Id")).Text != "")
{
Int32 add_user_Idstr = Convert.ToInt32(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_user_Id")).Text);
obj.add_user_Id = add_user_Idstr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_CreatedDate")).Text != "")
{
DateTime add_CreatedDatestr = Convert.ToDateTime(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_CreatedDate")).Text);
obj.add_CreatedDate = add_CreatedDatestr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_UpdatedDate")).Text != "")
{
DateTime add_UpdatedDatestr = Convert.ToDateTime(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_UpdatedDate")).Text);
obj.add_UpdatedDate = add_UpdatedDatestr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_DeletedDate")).Text != "")
{
DateTime add_DeletedDatestr = Convert.ToDateTime(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_DeletedDate")).Text);
obj.add_DeletedDate = add_DeletedDatestr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_IsDeleted")).Text != "")
{
Boolean add_IsDeletedstr = Convert.ToBoolean(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_IsDeleted")).Text);
obj.add_IsDeleted = add_IsDeletedstr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_IsPrimary")).Text != "")
{
Boolean add_IsPrimarystr = Convert.ToBoolean(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_IsPrimary")).Text);
obj.add_IsPrimary = add_IsPrimarystr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_cntm_Id")).Text != "")
{
Int32 add_cntm_Idstr = Convert.ToInt32(((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_cntm_Id")).Text);
obj.add_cntm_Id = add_cntm_Idstr;
}
if (((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_alt_No")).Text != "")
{
String add_alt_Nostr = ((TextBox)gvaddress_Master.FooterRow.FindControl("txtadd_alt_No")).Text;
obj.add_alt_No = add_alt_Nostr;
}
obj.Insertaddress_Master();
BindData();
lblException.Text = "";
}
catch(Exception ex)
{
lblException.Text = ex.Message.ToString();
}
}
Below is business method code:
public void Insertaddress_Master() {
try
{
DataAccess obj = new DataAccess();
obj.Provider = EnumProviders.SQLClient;
obj.ConnectionString = ConfigurationManager.ConnectionStrings["connStr"].ToString();
ParamStruct[] param = new ParamStruct[10];
param[0].direction = ParameterDirection.Input;
param[0].ParamName = "#add_Zip";
param[0].DataType = DbType.String;
param[0].value = _add_Zip;
param[1].direction = ParameterDirection.Input;
param[1].ParamName = "#add_FullAddress";
param[1].DataType = DbType.String;
param[1].value = _add_FullAddress;
param[2].direction = ParameterDirection.Input;
param[2].ParamName = "#add_user_Id";
param[2].DataType = DbType.Int32;
param[2].value = _add_user_Id;
param[3].direction = ParameterDirection.Input;
param[3].ParamName = "#add_CreatedDate";
param[3].DataType = DbType.DateTime;
param[3].value = _add_CreatedDate;
param[4].direction = ParameterDirection.Input;
param[4].ParamName = "#add_UpdatedDate";
param[4].DataType = DbType.DateTime;
param[4].value = _add_UpdatedDate;
param[5].direction = ParameterDirection.Input;
param[5].ParamName = "#add_DeletedDate";
param[5].DataType = DbType.DateTime;
param[5].value = _add_DeletedDate;
param[6].direction = ParameterDirection.Input;
param[6].ParamName = "#add_IsDeleted";
param[6].DataType = DbType.Boolean;
param[6].value = _add_IsDeleted;
param[7].direction = ParameterDirection.Input;
param[7].ParamName = "#add_IsPrimary";
param[7].DataType = DbType.Boolean;
param[7].value = _add_IsPrimary;
param[8].direction = ParameterDirection.Input;
param[8].ParamName = "#add_cntm_Id";
param[8].DataType = DbType.Int32;
param[8].value = _add_cntm_Id;
param[9].direction = ParameterDirection.Input;
param[9].ParamName = "#add_alt_No";
param[9].DataType = DbType.String;
param[9].value = _add_alt_No;
obj.ExecScalar("Insertaddress_Master", CommandType.StoredProcedure, param);
_returnBoolean = true;
}
catch (DataException ex)
{
_returnBoolean = false;
throw ex;
}
}
when I try to insert data using this code it generates exception saying " Procedure or function Insertaddress_Master has too many arguments specified". Can anyone help solving this problem.
I've read all previous thread on this topic but couldn't find appropriate solution yet.
SqlCommand objCommand = new SqlCommand();
you can recreate this object then it will work.
I got this answer.
You have two fields:
Is Deleted
Is Primarry
You have to passed the boolean that may have true/false.
Try passing 1 for true and 0 for false.
This should do the trick

Creating dynamic SQL DbParameter values

First time user - hoping this is in the right format:
I am wanting to know if I can create SQL DbParameter values, esp on the ParamaterName.
My current code is:
DbCommand dbCommand = SqlDb.GetStoredProcCommand(uspCommand);
DbParameter ProcessedFileName = dbCommand.CreateParameter();
ProcessedFileName.DbType = DbType.String;
ProcessedFileName.ParameterName = "#FileName";
ProcessedFileName.Value = pstrProcessedFileName;
dbCommand.Parameters.Add(ProcessedFileName);
I am wanting to add:
ProcessedFileName.ParameterName = "#FileName1";
ProcessedFileName.ParameterName = "#FileName2";
ProcessedFileName.ParameterName = "#FileName3";
ProcessedFileName.ParameterName = "#FileName4";
with the #FileNames coming from an array.
Something like this should work:
DbCommand dbCommand = SqlDb.GetStoredProcCommand(uspCommand);
foreach(String param in MyParameters)
{
DbParameter ProcessedFileName = dbCommand.CreateParameter();
ProcessedFileName.DbType = DbType.String;
ProcessedFileName.ParameterName = param;
ProcessedFileName.Value = pstrProcessedFileName;
dbCommand.Parameters.Add(ProcessedFileName);
}
best way to do this is put them in Dictionary, because you will need value also
Dictionary<string, string> params = new Dictionary<string,string>();
and just add them many as you want
params.Add("#FileName1", "my_filename")
etc...
and then
foreach(var param in params)
dbCommand.Parameters.AddWithValue(param.Key, param.Value);
Creating dynamic SQL DbParameter values
This is very helpful when you are going to create project where there is dynamic database, or may in future you are going to migrate / switch database .
Here is step by step solution
step 1) Create Parameter structure
public struct Parameter
{
public string ParameterName { get; set; }
public ParameterDirection Direction { get; set; }
public DbType DbType { get; set; }
public object Value { get; set; }
public string SourceColumn { get; set; }
public int Size { get; set; }
}
Step 2) Create database handling class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using System.Data.Common;
using MySql.Data.MySqlClient;
using MySql.Data;
using Oracle.DataAccess;
using Oracle.DataAccess.Client;
public class DBManagement
{
string connectionStr;
DbConnection con;
DbCommand cmd;
DbDataAdapter AD;
DataSet ds;
DbParameter[] sp;
IDBManagement Iobj = null;
public DBManagement()
{
this.Initialize();
}
void Initialize()
{
try
{
switch (ConfigurationManager.AppSettings["ActiveDatabase"].ToUpper())
{
case "MSSQL":
connectionStr = ConfigurationManager.ConnectionStrings["MSSQLConnectionString"].ConnectionString;
con = new SqlConnection();
cmd = new SqlCommand();
AD = new SqlDataAdapter();
break;
case "ORACLE":
connectionStr = ConfigurationManager.ConnectionStrings["OracleConnectionString"].ConnectionString;
con = new OracleConnection();
cmd = new OracleCommand();
AD = new OracleDataAdapter();
break;
case "MYSQL":
connectionStr = ConfigurationManager.ConnectionStrings["MYSQLConnectionString"].ConnectionString;
con = new MySqlConnection();
cmd = new MySqlCommand();
AD = new MySqlDataAdapter();
break;
default:
break;
}
con.ConnectionString = connectionStr;
cmd.Connection = con;
}
catch (Exception ex)
{
}
}
public DataSet ExecuteProcedure(string procName, CommandType cmdType, Parameter[] DBParameters = null)
{
try
{
cmd.CommandText = procName;
cmd.CommandType = cmdType;
cmd.Parameters.Clear();
if (DBParameters != null && DBParameters.Length > 0)
{
sp = DBParameters.ToParamerArray(cmd);
cmd.Parameters.AddRange(sp);
}
ds = new DataSet();
AD.SelectCommand = cmd;
AD.Fill(ds);
return ds;
}
catch (Exception ex)
{
throw ex;
}
}
}
Step 3) Convert parameter as per database
public static partial class GlobalExtensionFunctions
{
public static DbParameter[] ToParamerArray(this Parameter[] parameters,DbCommand cmd)
{
DbParameter[] sp = new DbParameter[parameters.Length];
int i = 0;
foreach (Parameter parameter in parameters)
{
// DbParameter p = cmd.CreateParameter();
sp[i] = cmd.CreateParameter();
sp[i].ParameterName = parameter.ParameterName;
sp[i].Value = parameter.Value;
sp[i].Direction = string.IsNullOrEmpty(Convert.ToString(parameter.Direction)) || parameter.Direction==0 ? ParameterDirection.Input : parameter.Direction;
sp[i].DbType = parameter.DbType;
sp[i].SourceColumn = parameter.SourceColumn;
sp[i].Size = parameter.Size;
i++;
}
return sp;
}
}
Step 4) Get Data
DBManagement c = new DBManagement();
public DataSet GetGetTestList(int testId)
{
Parameter[] p = new Parameter[1];
p[0].ParameterName = "#TestId";
p[0].Value = testId;
p[0].DbType = DbType.Int32;
return c.ExecuteProcedure(Procedures.TestDetails, CommandType.StoredProcedure,p);
}
Now use dataset or datatable and enjoy! :)
Abe - thanks - you got me in the right direction. Here is what I ended up doing:
inside my foreach loop, I'm calling my method:
foreach (DataRow row in GlobalClass.NAVdataTable.Rows)
{
GlobalClass.AddToDbCommand(ref dBCommand, row["FieldName"].ToString(), row["Value"].ToString());
connection.Open();
SqlDb.ExecuteNonQuery(dBCommand);
connection.Close();
dBCommand.Parameters.Clear();
}
and then my AddToDbCommand method contains:
public static void AddToDbCommand(ref DbCommand dbCommand, string FieldName, string FieldValue)
{
string FieldNameParameter = "#" + FieldName;
DbParameter dbParameter = dbCommand.CreateParameter();
dbParameter.ParameterName = FieldNameParameter;
dbParameter.Value = FieldValue;
dbCommand.Parameters.Add(dbParameter);
}
Refactored as an extension to DbCommand, also fieldName is left without #, so you need to pass # or : prefixes and fieldValue is set to object type (not only string).
public static class DbCommandExtensions
{
public static void AddParam(this DbCommand dbCommand, string fieldName, object fieldValue)
{
string fieldNameParameter = fieldName;
DbParameter dbParameter = dbCommand.CreateParameter();
dbParameter.ParameterName = fieldNameParameter;
dbParameter.Value = fieldValue;
dbCommand.Parameters.Add(dbParameter);
}
}

Insert Query in C# using Parameters

Am trying to insert several columns into my database using the following insert query from C# but it throws the exception somehow somewhere and my guess is there are no values provided for insertion. i just want to confirm that and find out how i can fix the insert statement. i have a picture below that displays what is passed into the parameters at runtime. i used a break point to get this info.
need your expertise at this one...thanks
if (Page.IsValid)
{
DateTime exhibitDate = DateTime.Now;
int caseid = Convert.ToInt32(CaseIDDropDownList.SelectedItem.Text);
string exhibittype = exhibitTypeTextBox.Text.ToString();
string storedloc = storedLocationTextBox.Text.ToString();
string offid = DropDownList1.SelectedItem.Text.ToString();
Stream imgStream = exhibitImageFileUpload.PostedFile.InputStream;
int imgLen = exhibitImageFileUpload.PostedFile.ContentLength;
byte[] imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData,0,imgLen);
try
{
SqlConnection connections = new SqlConnection(strConn);
SqlCommand command = new SqlCommand("INSERT INTO Exhibits (CaseID, ExhibitType, ExhibitImage, DateReceived, StoredLocation, InvestigationStatus, OfficerID, SuspectID, InvestigatorID, ManagerID, AdminID ) VALUES (#CaseID, #ExhibitType, #ExhibitImage, #DateReceived, #StoredLocation, #InvestigationStatus, #OfficerID, #SuspectID, #InvestigatorID, #ManagerID, #AdminID)", connections);
SqlParameter param0 = new SqlParameter("#CaseID", SqlDbType.Int);
param0.Value = caseid;
command.Parameters.Add(param0);
SqlParameter param1 = new SqlParameter("#ExhibitType", SqlDbType.NText);
param1.Value = exhibittype;
command.Parameters.Add(param1);
SqlParameter param2 = new SqlParameter("#ExhibitImage", SqlDbType.Image);
param2.Value = imgBinaryData;
command.Parameters.Add(param2);
SqlParameter param3 = new SqlParameter("#DateReceived", SqlDbType.SmallDateTime);
param3.Value = exhibitDate;
command.Parameters.Add(param3);
SqlParameter param4 = new SqlParameter("#StoredLocation", SqlDbType.NText);
param4.Value = storedloc;
command.Parameters.Add(param4);
SqlParameter param5 = new SqlParameter("#InvestigationStatus", SqlDbType.VarChar, 50);
param5.Value = "";
command.Parameters.Add(param5);
SqlParameter param6 = new SqlParameter("#OfficerID", SqlDbType.NChar, 10);
param6.Value = offid;
command.Parameters.Add(param6);
SqlParameter param7 = new SqlParameter("#SuspectID", SqlDbType.NChar, 10);
param7.Value = null;
command.Parameters.Add(param7);
SqlParameter param8 = new SqlParameter("#InvestigatorID", SqlDbType.NChar, 10);
param8.Value = null;
command.Parameters.Add(param8);
SqlParameter param9 = new SqlParameter("#ManagerID", SqlDbType.NChar, 10);
param9.Value = null;
command.Parameters.Add(param9);
SqlParameter param10 = new SqlParameter("#AdminID", SqlDbType.NChar, 10);
param10.Value = adminID;
command.Parameters.Add(param10);
connections.Open();
int numRowsAffected = command.ExecuteNonQuery();
connections.Close();
if (numRowsAffected != 0)
{
Response.Write("<BR>Rows Inserted successfully");
CaseIDDropDownList.ClearSelection();
exhibitTypeTextBox.Text = null;
storedLocationTextBox.Text = null;
DropDownList1.ClearSelection();
}
else
{
Response.Write("<BR>An error occurred uploading the image");
}
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
}
the exception is as follows
$exception {"The parameterized query '(#CaseID int,#ExhibitType ntext,#ExhibitImage image,#DateReceive' expects the parameter '#SuspectID', which was not supplied."} System.Exception {System.Data.SqlClient.SqlException}
If you want to pass in NULL for your database / parameter type, you need to use DBNull.Value like this:
SqlParameter param9 = new SqlParameter("#ManagerID", SqlDbType.NChar, 10);
param9.Value = DBNull.Value;
command.Parameters.Add(param9);
Do this wherever you're setting something to null right now, and I'm pretty sure it'll work just fine. Everything is looking okay.
You can do this much easier, try it as such:
if (Page.IsValid)
{
DateTime exhibitDate = DateTime.Now;
int caseid = Convert.ToInt32(CaseIDDropDownList.SelectedItem.Text);
string exhibittype = exhibitTypeTextBox.Text.ToString();
string storedloc = storedLocationTextBox.Text.ToString();
string offid = DropDownList1.SelectedItem.Text.ToString();
Stream imgStream = exhibitImageFileUpload.PostedFile.InputStream;
int imgLen = exhibitImageFileUpload.PostedFile.ContentLength;
byte[] imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData,0,imgLen);
try
{
SqlConnection connections = new SqlConnection(strConn);
SqlCommand command = new SqlCommand("INSERT INTO Exhibits (CaseID, ExhibitType, ExhibitImage, DateReceived, StoredLocation, InvestigationStatus, OfficerID, SuspectID, InvestigatorID, ManagerID, AdminID ) VALUES (#CaseID, #ExhibitType, #ExhibitImage, #DateReceived, #StoredLocation, #InvestigationStatus, #OfficerID, #SuspectID, #InvestigatorID, #ManagerID, #AdminID)", connections);
command.Parameters.AddWithValue("#CaseID", caseid);
//and so on for your 10 parameters
connections.Open();
int numRowsAffected = command.ExecuteNonQuery();
connections.Close();
if (numRowsAffected != 0)
{
Response.Write("<BR>Rows Inserted successfully");
CaseIDDropDownList.ClearSelection();
exhibitTypeTextBox.Text = null;
storedLocationTextBox.Text = null;
DropDownList1.ClearSelection();
}
else
{
Response.Write("<BR>An error occurred uploading the image");
}
}
catch (Exception ex)
{
string script = "<script>alert('" + ex.Message + "');</script>";
}
}
I'm not sure if this will actually fix what is happening without knowing the exact exception. If you could provide the actual exception that would help a lot.

Categories

Resources