The error is cannot convert object to sql parameter
I'm working with a bol->dal, building an array of parameters to pass to the dal:
bol:
SqlParameter[] sqlParams = new SqlParameter[]
{
new SqlParameter("#p1", SqlDbType.VarChar, 30).Value = "val1",
new SqlParameter("#p2", SqlDbType.VarChar, 30).Value = "val2"
};
dal:
public static int ExecuteNonQuery(string sql, SqlParameter[] #params)
{
SqlConnection cnn = new SqlConnection(connectionstring);
SqlCommand cmd = new SqlCommand(sql, cnn);
for (int i = 0; i <= #params.Length - 1; i++)
{
cmd.Parameters.Add(#params[i]);
}
foreach (IDataParameter param in cmd.Parameters)
{
if (param.Value == null) param.Value = DBNull.Value;
}
cnn.Open();
int retval = cmd.ExecuteNonQuery();
cnn.Close();
return retval;
}
I need help improving this, thanks--
You need to pass in the actual SqlParameter. Notice the object initializer of the Value:
var sqlParams = new SqlParameter[]
{
new SqlParameter("#p1", SqlDbType.VarChar, 30) {Value = "val1"},
new SqlParameter("#p2", SqlDbType.VarChar, 30) {Value = "val2"},
};
Related
try
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
SqlParameter[] pram = new SqlParameter[7];
pram[0] = new SqlParameter("#fname", SqlDbType.VarChar, 50);
pram[1] = new SqlParameter("#lname", SqlDbType.VarChar, 50);
pram[2] = new SqlParameter("#dob", SqlDbType.VarChar, 50);
pram[3] = new SqlParameter("#gender", SqlDbType.Char, 10);
pram[4] = new SqlParameter("#fathername", SqlDbType.VarChar, 50);
pram[5] = new SqlParameter("#contact", SqlDbType.Int, 100);
pram[6] = new SqlParameter("#address", SqlDbType.VarChar, 50);
pram[0].Value = fname;
pram[1].Value = lname;
pram[2].Value = dob;
pram[3].Value = gender;
pram[4].Value = fathername;
pram[5].Value = contact;
pram[6].Value = address;
for (int i = 0; i < pram.Length; i++)
{
cmd.Parameters.Add(pram[i]);
}
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch(System.Data.SqlClient.SqlException ex_msg)
{
string msg = "Error occured while inserting";
msg += ex_msg.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
}
Error received:
Failed to convert parameter value from a String to a Int32
You are probably passing a value that can't be parsed into an int for this parameter:
pram[5] = new SqlParameter("#contact", SqlDbType.Int, 100);
Check what you are passing here:
pram[5].Value = contact;
If contact is a string then do something like:
int contactNumber;
pram[5].Value = int.TryParse(contact, out contactNumber) ? contactNumber : 0;
Thanks to some tips and reminders here, I changed my code from this kludgy mess:
try
{
DataSet dsUsage = new DataSet();
SqlConnection conn = new SqlConnection("SERVER=PROSQL05;DATABASE=platypusdata;UID=duckbill;PWD=poisonToe42;Connection Timeout=0");
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = String.Format("Exec sp_ViewProductUsage_MappingRS '{0}', '{1}', '{2}'", mammal, dateBegin, dateEnd);
da.SelectCommand = cmd;
conn.Open();
da.Fill(dsUsage);
conn.Close();
DataTable dtUsage = dsUsage.Tables[0];
if (dtUsage.Rows.Count > 0)
{
foreach (DataRow productUsageByMonthDataRow in dtUsage.Rows)
{
. . .
...to this:
try
{
SqlDataAdapter da = new SqlDataAdapter();
DataSet dsUsage = new DataSet();
using (SqlConnection conn = new SqlConnection(UsageRptConstsAndUtils.PlatypusConnStr))
{
using (SqlCommand cmd = new SqlCommand("sp_ViewProductUsage_MappingRS", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Unit", SqlDbType.VarChar).Value = _unit;
cmd.Parameters.Add("#BegDate", SqlDbType.DateTime).Value = dtBegin;
cmd.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = dtEnd;
da.SelectCommand = cmd;
conn.Open();
//cmd.ExecuteReader(); <- Is this even necessary?
da.Fill(dsUsage);
}
}
DataTable dtUsage = dsUsage.Tables[0];
if (dtUsage.Rows.Count > 0)
{
// Populate the cells
foreach (DataRow productUsageByMonthDataRow in dtUsage.Rows)
{
. . .
Note that I have SqlCommand's ExecuteReader commented out in the new code because it seems unnecessary due to the SqlDataAdapter being provided the SqlCommand. It works fine. So: am I correct in assuming I can remove cmd.ExecuteReader() altogether? Is there any benefit in retaining it, or would that be totally redundant and create "busy work" for the process?
UPDATE
So, to pass an array of SqlParameter (to the ExecuteDataSet method in MethodMan's answer), I take it that I would first have to do something like:
SqlParameter sqlp = new SqlParameter();
sqlp.ParameterName = "Unit";
sqlp.Value = _unit;
cmd.Parameters.Add(sqlp);
...etc. (and then add them to an array - or, possibly better a generic list of SqlParameter).
UPDATE 2
I just ran into this for the first time: if you use MethodMan's example (which I do) and you use a parameterless query, you need to bypass the parameter-adding loop like so:
if (null != parameters)
{
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
}
I would personally create a SqlDBHelper class and pass call the stored procedure using a method such as this
public static class SqlDBHelper
{
public static DataSet ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
{
using (DataSet ds = new DataSet())
using (SqlConnection connStr = new SqlConnection(ConfigurationManager.ConnectionStrings["DbConn"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, connStr))
{
cmd.CommandType = cmdType;
foreach (var item in parameters)
{
cmd.Parameters.Add(item);
}
try
{
cmd.Connection.Open();
new SqlDataAdapter(cmd).Fill(ds);
}
catch (SqlException ex)
{
//log to a file or write to Console for example
Console.WriteLine(ex.Message);
}
return ds;
}
}
}
If you want to return a DataTable then change the return type in the Method signature and call the following in the return statement below
public static DataTable ExecuteDataSet(string sql, CommandType cmdType, params SqlParameter[] parameters)
return ds.Tables[0];
Here is an example on how you would call the method
someDataTable = SqlDBHelper.ExecuteDataSet("sp_ViewProductUsage_MappingRS", CommandType.StoredProcedure,
new SqlParameter() { ParameterName = "#Unit", SqlDbType = SqlDbType.VarChar, Value = _unit },
new SqlParameter() { ParameterName = "#BegDate", SqlDbType = SqlDbType.DateTime, Value = dtBegin },
new SqlParameter() { ParameterName = "#EndDate", SqlDbType = SqlDbType.DateTime, Value = dtEnd }
);
I am trying to create a SqlParameterCollection, but gives error while adding some SqlParameter in sp.Add() method.
Please help me how to add parameter and how to pass it to my another function where I declare a SqlConnection and SqlCommand.
SqlParameterCollection sp = null;
sp.Add(new SqlParameter("#CmpyCode", SqlDbType.NVarChar)).Value = CV.Global.CMPYCODE;
sp.Add(new SqlParameter("#Code", SqlDbType.NVarChar)).Value = codeName;
sp.Add(new SqlParameter("#DisplayCode", SqlDbType.NVarChar)).Value = codeName + "-";
sp.Add(new SqlParameter("#TotalDigit", SqlDbType.Int)).Value = CV.Global.PARAMTOTALDIGIT;
insertData("<Sp Name>", sp);
My another function is insertData(...)
internal static int insertData(string spName, SqlParameterCollection sp)
{
int retObj = 0;
using (SqlConnection con = new SqlConnection(CV.Global.CONSTRING))
{
try
{
con.Open();
SqlCommand cmd = new SqlCommand(spName, con);
cmd.CommandType = CommandType.StoredProcedure;
if (sp.Count > 0)
{
foreach (SqlParameter param in sp)
cmd.Parameters.Add(param);
}
retObj = cmd.ExecuteNonQuery();
}
catch (Exception ev)
{
Util.Log(ev);
throw;
}
finally
{
try
{
con.Close();
}
catch (Exception ev) { Util.Log(ev); throw; }
}
}
return retObj;
}
I am trying to create a SqlParameterCollection and passed it to the insertData function. But it throws an error while I am calling sp.Add() method in my first function.
The error is
Object reference not set to an instance of an object
You cannot use any variable like SqlParameterCollection (a reference object) without a call to its constructor (new), but the SqlParameterCollection is an object that cannot be initialized directly with a new. It has no public constructor and can be retrieved only from the property of an existant SqlCommand.
SqlCommand cmd = new SqlCommand(commandText, connection);
SqlParameterCollection sp = cmd.Parameters;
I suggest to change your InsertData method to accept a List<SqlParameter> and let it handle the adding of the parameters to the SqlCommand that executes the command text
List<SqlParameter> sp = new List<SqlParameter>()
{
new SqlParameter() {ParameterName = "#CmpyCode", SqlDbType = SqlDbType.NVarChar, Value= CV.Global.CMPYCODE},
new SqlParameter() {ParameterName = "#Code", SqlDbType = SqlDbType.NVarChar, Value = codeName},
new SqlParameter() {ParameterName = "#DisplayCode", SqlDbType = SqlDbType.NVarChar, Value = codeName + "-"},
new SqlParameter() {ParameterName = "#TotalDigit", SqlDbType = SqlDbType.Int, Value = CV.Global.PARAMTOTALDIGIT}
};
insertData(CV.Sps.SP_INSERT_PARAM_TABLE, sp);
and insertData simply receives an optional list of SqlParameter and add them to the internal SqlCommand parameter collection if needed
internal static int insertData(string spName, List<SqlParameter> sp = null)
{
....
if(sp != null)
cmd.Parameters.AddRange(sp.ToArray());
....
}
Here is a simplified answer. I use this type of thing for a dynamic SQL query with dynamic parameters. Sometimes you don't need all parameters if you are writing a dynamic sqlquery when determining if a variable has a value.
List<SqlParameter> paramList = new List<SqlParameter>();
paramList.Add(new SqlParameter("#StartDate", StartDate));
paramList.Add(new SqlParameter("#EndDate", EndDate));
if (TicketID != "" && TicketID != null && TicketID != "undefined")
{
paramList.Add(new SqlParameter("#TicketID", TicketID));
SQLQuery = SQLQuery + " AND A.TicketID = #TicketID";
}
var Parameters = paramList.ToArray();
List<Report> ReportList = db.Database.SqlQuery<Report>(SQLQuery, Parameters).ToList();
I want to insert data from a dataset in asp.net into a SQL Server table.
But I can't pass the values from dataset to my stored procedure plz help me
Here is my code
private static SqlCommand WriteDatabase(SqlConnection conn)
{
SqlCommand cmd = new SqlCommand(SP_insertData);
cmd.Parameters.Clear();
cmd.CommandType = CommandType.StoredProcedure;
SqlParameterCollection pc = cmd.Parameters;
pc.Add(CreateParameter("abID", System.Data.SqlDbType.Int));
pc.Add(CreateParameter("fHitType", System.Data.SqlDbType.Int));
pc.Add(CreateParameter("DateOfHit", System.Data.SqlDbType.DateTime));
pc.Add(CreateParameter("TimeOfHit", System.Data.SqlDbType.Int));
pc.Add(CreateParameter("fEmpid", System.Data.SqlDbType.Int));
cmd.ExecuteNonQuery();
return cmd;
}
private static SqlParameter CreateParameter(string p, SqlDbType sqlDbType)
{
SqlParameter parameter = new SqlParameter("#" + p, sqlDbType);
parameter.SourceColumn = p;
return parameter;
}
I can't pass values from dataset to my stored procedure
Have you try this code:
SqlConnection oConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString);
public Boolean InserData(string abID, string fHitType,string DateOfHit, string TimeOfHit,string fEmpid)
{
// SqlConnection oConnection = new SqlConnection("Connection_String");
SqlCommand oCommand = new SqlCommand();
oCommand.Connection = oConnection;
oCommand.CommandText = "SP_insertData";
oCommand.CommandType = CommandType.StoredProcedure;
oCommand.Parameters.AddWithValue("#abID", abID);
oCommand.Parameters.AddWithValue("#fHitType", fHitType);
oCommand.Parameters.AddWithValue("#DateOfHit", DateOfHit);
oCommand.Parameters.AddWithValue("#TimeOfHit", TimeOfHit);
oCommand.Parameters.AddWithValue("#fEmpid", fEmpid);
oConnection.Open();
Boolean Result = Convert.ToBoolean(oCommand.ExecuteNonQuery());
oConnection.Close();
return Result;
}
It will return true or false Returns true means your data has been saved successfully and return false means not saved...
Please Try it
SqlConnection oConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString);
public int InserData(string abID, string fHitType, string DateOfHit, string TimeOfHit, string fEmpid)
{
SqlCommand oCommand = new SqlCommand("SP_insertData", oConnection);
oCommand.CommandType = CommandType.StoredProcedure;
oCommand.Parameters.AddWithValue("#abID", abID);
oCommand.Parameters.AddWithValue("#fHitType", fHitType);
oCommand.Parameters.AddWithValue("#DateOfHit", DateOfHit);
oCommand.Parameters.AddWithValue("#TimeOfHit", TimeOfHit);
oCommand.Parameters.AddWithValue("#fEmpid", fEmpid);
oConnection.Open();
int Result = oCommand.ExecuteNonQuery();
oConnection.Close();
return Result;
}
if Return Type 1 then suceess else not insert Successfully
I do not clearly understand how to format the SqlDataAdapter for output variables when working with C#
Error Message:
Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
Code Example (Stored Procedure works fine):
private DataTable updateOrdEodHold(DataTable tb, out string mnpft,
out string authld, out string trd, out string hld, out string extnow)
{
// Start the connection string.
string connstr = ConfigurationManager.ConnectionStrings
["LocalSqlServer"].ConnectionString;
SqlConnection myConn = new SqlConnection(connstr);
// Declare symbol and assign for Errors Catch Exception.
string Symbol = "";
string sqlComm = "dbo.UpdateOrdEodHold";
DataTable HoldVals = new DataTable();
SqlDataAdapter dataAdp = new SqlDataAdapter(sqlComm, myConn);
dataAdp.SelectCommand.CommandType = CommandType.StoredProcedure;
string ticker = (string)Convert.ToString(tb.Rows[0]["Ticker"]);
// update Symbol for Catch ex
Symbol = ticker.ToString();
String company = (string)Convert.ToString(tb.Rows[0]["Company"]);
String avgprofit = (string)Convert.ToString(tb.Rows[0]["AvgProfit"]);
String extdte = (string)Convert.ToString(tb.Rows[0]["ExitDate"]);
dataAdp.SelectCommand.Parameters.Clear();
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#ticker",
SqlDbType.VarChar, 10));
dataAdp.SelectCommand.Parameters["#ticker"].Value =
(string)ticker.ToString();
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#company",
SqlDbType.VarChar, 25));
dataAdp.SelectCommand.Parameters["#company"].Value =
(string)company.ToString();
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#avgpft",
SqlDbType.VarChar, 10));
dataAdp.SelectCommand.Parameters["#avgpft"].Value =
(string)avgprofit.ToString();
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#mnpft",
SqlDbType.VarChar, 10));
dataAdp.SelectCommand.Parameters["#mnpft"].Direction =
ParameterDirection.Output;
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#authld",
SqlDbType.VarChar, 6));
dataAdp.SelectCommand.Parameters["#authld"].Direction =
ParameterDirection.Output;
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#hld",
SqlDbType.VarChar, 6));
dataAdp.SelectCommand.Parameters["#hld"].Direction =
ParameterDirection.Output;
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#trd",
SqlDbType.VarChar, 6));
dataAdp.SelectCommand.Parameters["#trd"].Direction =
ParameterDirection.Output;
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#extnow",
SqlDbType.VarChar, 6));
dataAdp.SelectCommand.Parameters["#extnow"].Direction =
ParameterDirection.Output;
dataAdp.SelectCommand.Parameters.Add(new SqlParameter("#extdte",
SqlDbType.VarChar, 15));
dataAdp.SelectCommand.Parameters["#extdte"].Value =
(string)extdte.ToString();
dataAdp.Fill(HoldVals);
mnpft = HoldVals.Rows[0]["MinProfit"].ToString();
authld = HoldVals.Rows[0]["AutoHold"].ToString();
trd = HoldVals.Rows[0]["Trade"].ToString();
hld = HoldVals.Rows[0]["Hold"].ToString();
extnow = HoldVals.Rows[0]["ExitNow"].ToString();
return HoldVals;
}
You need to hold a reference to the Output parameter variable so that you can access the value returned to it using parameter.Value once the adapter has executed the command.
//Create the parameter
SqlParameter parameter = new SqlParameter("#mnpft", SqlDbType.VarChar);
//Set the parameter direction as output
parameter.Direction = ParameterDirection.Output;
sqlCommand.Parameters.Add(parameter);
SqlDataAdapter sqlAdapter = new SqlDataAdapter(sqlCommand);
sqlAdapter.Fill(dataSet);
//Fetch the output parameter after doing the Fill
string outputValue = Convert.ToString(parameter.Value);