foreach (DataRow masterRow in dst.Tables["Menu"].Rows)
{
MenuItem masterItem = new MenuItem((string)masterRow["Parentitem"]);
string mp = masterItem.Value;
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "#mp";
parameter.SqlDbType = SqlDbType.NVarChar;
parameter.Direction = ParameterDirection.Input;
parameter.Value = mp;
string q = "select aspnet_PersonalizationPerUser.hasRights
from Menu,aspnet_Users,aspnet_Paths, aspnet_PersonalizationPerUser
where Menu.Parentitem=#mp and Menu.Url = aspnet_Paths.Path
and aspnet_Paths.PathId =aspnet_PersonalizationPerUser.PathId
and aspnet_Users.UserName ='admin'
and aspnet_PersonalizationPerUser.UserId = aspnet_Users.userId ";
SqlCommand cm = new SqlCommand(q, conn);
string b = (string)cm.ExecuteScalar();
if (b == "true")
{
Menu1.Items.Add(masterItem);
}
So when I run the app it says need to declare scalar variable mp .. can u let me know the mistake?
You need to add the parameter to the command.
SqlCommand cm = new SqlCommand(q, conn);
cmd.Parameters.Add(parameter);
string b = (string)cm.ExecuteScalar();
You need to actually add the parameter to the SqlCommand object.
Off the top of my head I think its something like:
cm.Parameters.Add(parameter);
Do this before you call ExecuteScalar
You are just creating a parameter, not adding it to your command. Try adding this before executing the command:
cm.Parameters.Add(parameter);
You have forgot to add the parameter #mp to your command
cm.Parameters.Add(parameter)
Related
I have this situation: in DataEntryForm I have a dropdownlist, where user selects a letter number, and according to that inserts other related data.
I plan to change letter's status in other table by choosing in dropdownlist automatically.
I am using this code:
SqlParameter answertoparam = new SqlParameter("answerto", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID ='2' where income_number=('" + ansTo + "' )";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
comm.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
comm.ExecuteNonQuery();
Unfortunately, the result is nothing.
Server is not giving error, and it simply refreshes the page that is it.
In your posted code, you are passing the SqlParameter as well as passing the value as raw data. Do either of one and preferably pass it as SqlParameter like
SqlParameter answertoparam = new SqlParameter("answertoparam", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID = '2' where income_number = #answertoparam";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
findincomelett.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
Moreover, you have two SqlCommand object in place and calling two ExecuteNonQuery() on them. correct that ... see below
SqlCommand findincomelett = new SqlCommand(commandText, conn); --1
comm.Parameters.Add(answertoparam); --2
conn.Open();
findincomelett.ExecuteNonQuery(); --1
comm.ExecuteNonQuery(); --2
As far as I understand, the issue is that the correct IncomeLetters.docState_ID is not updated to '2'.
You may want to debug and see what value you are getting in :
string ansTo = ddlAnswerTo.SelectedItem.Value;
The record in the database that you are expecting to be updated may not have the record that satisfies the where clause 'income_number = #answertoparam'
I would like to bring you here full code of the page.
Idea is: I have page for enrollment. I am passing data to DB through stored procedure (DataInserter).
Problem is here: during enrollment, user selects from dropdownlist number of the letter he would like to answer to, and in the end, the status of the letter on other table of DB (IncomeLetters.tbl), would change from "pending"('1') to "issued" ('2').
I guess, I could clear my point to you and thank you for your support!
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MaktubhoConnectionString2"].ConnectionString);
using (SqlCommand comm = new SqlCommand("DataInserter", conn))
{
comm.CommandType = CommandType.StoredProcedure;
comm.Connection = conn;
SqlParameter employeeparam = new SqlParameter("EmployeeSentIndex", int.Parse(ddlemployee.SelectedItem.Value));
SqlParameter doctypeparam = new SqlParameter("doctype_ID", int.Parse(ddldoctype.SelectedItem.Value));
SqlParameter doccharparam = new SqlParameter("docchar_ID", int.Parse(ddldocchar.SelectedItem.Value));
SqlParameter authorityparam = new SqlParameter("authority", txtauthority.Text);
SqlParameter subjectparam = new SqlParameter("subject", txtsubject.Text);
DateTime dt = DateTime.Now;
string todasdate = dt.ToString("d", CultureInfo.CreateSpecificCulture("de-DE"));
SqlParameter entrydateparam = new SqlParameter("entrydate", todasdate);
string Pathname = "UploadImages/" + Path.GetFileName(FileUpload1.PostedFile.FileName);
SqlParameter imagepathparam = new SqlParameter("image_path", Pathname);
SqlParameter loginparam = new SqlParameter("login", "jsomon");
comm.Parameters.Add(employeeparam);
comm.Parameters.Add(doctypeparam);
comm.Parameters.Add(doccharparam);
comm.Parameters.Add(authorityparam);
comm.Parameters.Add(subjectparam);
comm.Parameters.Add(entrydateparam);
comm.Parameters.Add(imagepathparam);
comm.Parameters.Add(loginparam);
comm.Parameters.Add("#forlabel", SqlDbType.VarChar, 100);
comm.Parameters["#forlabel"].Direction = ParameterDirection.Output;
FileUpload1.SaveAs(Server.MapPath("~/UploadImages/" + FileUpload1.FileName));
string ansTo = ddlAnswerTo.SelectedItem.Value;
SqlParameter answertoparam = new SqlParameter("answertoparam", ansTo);
string commandText = "update IncomeLetters set IncomeLetters.docState_ID = '2' where income_number = #answertoparam";
SqlCommand findincomelett = new SqlCommand(commandText, conn);
findincomelett.Parameters.Add(answertoparam);
conn.Open();
findincomelett.ExecuteNonQuery();
comm.ExecuteNonQuery();
lblresult.Visible = true;
Image1.Visible = true;
lblresult.Text = "Document number:";
lblnumber.Visible = true;
lblnumber.Text = (string)comm.Parameters["#forlabel"].Value; ;
conn.Close();
}
txtauthority.Text = "";
txtsubject.Text = "";
}
I know that this question has been asked many times and I have spend my 2 hours reading the solution on SO and other websites but couldn't solved it. So, please don't mark it as duplicate Here is my code:-
dt = new DataTable();
dt = con.GetDataTable("select * from Panbnk_tran_t where emp_code='" + emp_code + "'", "Panbnk_tran_t");
if (dt.Rows.Count > 0)
{
string qry = "";
qry="insert into Panbnk_arc_t ";
qry +="(panid, cancel_checqe)";
qry += "values( #PanId, #Cancel_checqe)";
cmd = new OleDbCommand();
cmd.Parameters.Add("#PanId", SqlDbType.Image).Value = dt.Rows[0]["panid"];
cmd.Parameters.Add("#Cancel_checqe", SqlDbType.Image).Value = dt.Rows[0]["cancel_checqe"];
cmd = new OleDbCommand(qry, con.cnn);
cmd.ExecuteNonQuery();
}
EDIT:
using (var cmd = new OleDbCommand(qry, con.cnn))
{
cmd.Parameters.Add("#PanId", SqlDbType.Image).Value = dt.Rows[0]["panid"];
cmd.Parameters.Add("#Cancel_checqe", SqlDbType.Image).Value = dt.Rows[0]["cancel_checqe"];
cmd.ExecuteNonQuery();
}
I have tried this but same error again
Both the fields are image type
dt = new DataTable();
dt = con.GetDataTable("select * from Panbnk_tran_t where emp_code='" + emp_code + "'", "Panbnk_tran_t");
if (dt.Rows.Count > 0)
{
string qry = "";
byte[] imgbytePan, imgbytecheque;
imgbytePan = (byte[])dt.Rows[0]["panid"];
imgbytecheque = (byte[])dt.Rows[0]["cancel_checqe"];
qry = "insert into Panbnk_arc_t ";
qry += "(panid, cancel_checqe)";
qry += "values( ?, ?)";
cmd = new OleDbCommand(qry, con.cnn);
cmd.Parameters.Add("#imgPan", SqlDbType.Image).Value = imgbytePan;
cmd.Parameters.Add("#imgChq", SqlDbType.Image).Value = imgbytecheque;
cmd.ExecuteNonQuery();
}
EDIT :
If you use sqlcommand then there is no need to use ? placeholders. Since OleDbCommand and OdbcCommand does not support named parameters, and use ? placeholders instead. For SqlCommand, it doesn't really care about the order of the parameters on your object so long as those parameters exist in the query.
For better explanation you can visit here.
Hope this made you clear.
The problem on that line;
cmd = new OleDbCommand(qry, con.cnn);
You are re-create an OleDbCommand object but it's CommandText still expects #PanId and #Cancel_checqe parameters since you try to execute it.
When you create your first cmd in cmd = new OleDbCommand(); line, use that query as a parameter in it's constructor as cmd = new OleDbCommand(qry); and delete cmd = new OleDbCommand(qry, con.cnn); line.
Also in your select statement you are putting your value in your command with string concatenation. Do not do that! You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your database connections and commands.
using(var cmd = new OleDbCommand(qry, con.cnn))
{
cmd.Parameters.Add("#PanId", SqlDbType.Image).Value = dt.Rows[0]["panid"];
cmd.Parameters.Add("#Cancel_checqe", SqlDbType.Image).Value = dt.Rows[0]["cancel_checqe"];
con.cnn.Open();
cmd.ExecuteNonQuery();
}
You have defined Command object twice. Which overwrites the parameter added in previous object
cmd = new OleDbCommand(); // defined once
cmd.Parameters.Add("#PanId", SqlDbType.Image).Value = dt.Rows[0]["panid"];
cmd.Parameters.Add("#Cancel_checqe", SqlDbType.Image).Value = dt.Rows[0]["cancel_checqe"];
cmd = new OleDbCommand(qry, con.cnn); //defined again
cmd.ExecuteNonQuery();
Define cmd only once.
cmd = new OleDbCommand(qry, con.cnn);
cmd.Parameters.Add("#PanId", SqlDbType.Image).Value = dt.Rows[0]["panid"];
cmd.Parameters.Add("#Cancel_checqe", SqlDbType.Image).Value = dt.Rows[0]["cancel_checqe"];
cmd.ExecuteNonQuery();
I am getting the exception "Must declare the scalar variable"#strAccountID"
string #straccountid = string.Empty;
sSQL =
"SELECT GUB.BTN,
GUP.CUST_USERNAME,
GUP.EMAIL
FROM GBS_USER_BTN GUB,
GBS_USER_PROFILE GUP
WHERE GUB.CUST_UID = GUP.CUST_UID
AND GUB.BTN = '#straccountID'
ORDER BY
CREATE_DATE DESC"
#straccountid = strAccountID.Substring(0, 10);
Code For running the query against the DB
try
{
oCn = new SqlConnection(ConfigurationSettings.AppSettings["GBRegistrationConnStr"].ToString());
oCn.Open();
oCmd = new SqlCommand();
oCmd.Parameters.AddWithValue("#strAccountID", strAccountID);
oCmd.CommandText = sSQL;
oCmd.Connection = oCn;
oCmd.CommandType = CommandType.Text;
oDR = oCmd.ExecuteReader(CommandBehavior.CloseConnection);
I already declared the variable. Is there any flaw in my query?
First off the bat get rid of these two lines:
string #straccountid = string.Empty;
#straccountid = strAccountID.Substring(0, 10);
and then try this code:
string strAccountID = "A1234"; //Create the variable and assign a value to it
string AcctID = strAccountID.Substring(0, 10);
oCn = new SqlConnection(ConfigurationSettings.AppSettings["GBRegistrationConnStr"].ToString());
oCn.Open();
oCmd = new SqlCommand();
oCmd.CommandText = sSQL;
oCmd.Connection = oCn;
oCmd.CommandType = CommandType.Text;
ocmd.Parameters.Add("straccountid", AcctID); //<-- You forgot to add in the parameter
oDR = oCmd.ExecuteReader(CommandBehavior.CloseConnection);
Here is a link on how to create Parametized Query: http://www.dotnetperls.com/sqlparameter
You've declared #straccountid but not as part of the SQL. The SQL server only sees what you send to it. You'd be better off using SQLCommand and parameters to build your select statement safely. This post has examples.
procedure select_card_transaction(trans_id nvarchar2,
usr_id number,
Quantity out number) is
begin
select count(*)
into Quantity
from user_cards u
where u.transaction_id = trans_id
and u.user_id = usr_id;
end;
and Consuming it:
using(var conn = new OracleConnection(Settings.Default.OraWUConnString))
{
var cmd = conn.CreateCommand();
cmd.CommandText = "for_temporary_testing.select_card_transaction";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("trans_id", TransactionID);
cmd.Parameters.AddWithValue("usr_id", UserID);
var q = new OracleParameter("Quantity", OracleType.Number);
q.Direction = ParameterDirection.Output;
cmd.Parameters.Add(q);
//cmd.Parameters[0].OracleType = OracleType.NVarChar;
//cmd.Parameters[1].OracleType = OracleType.Number;
conn.Open();
var obj = cmd.ExecuteNonQuery();
conn.Close();
return (int)q.Value == 1;
}
It returns the following error.
ORA-06550 wrong number or types of arguments when calling Oracle stored procedure...
ANY IDEA?
I have had the same problem before. Are you using the ODP.Net drivers? I was able to solve the problem by adding the output parameter first. This needs to be done before the input parameters. In your case it would look like
using(var conn = new OracleConnection(Settings.Default.OraWUConnString))
{
conn.Open();
var cmd = conn.CreateCommand();
cmd.CommandText = "for_temporary_testing.select_card_transaction";
cmd.CommandType = CommandType.StoredProcedure;
// Return value parameter has to be added first !
var Quantity = new OracleParameter();
Quantity.Direction = ParameterDirection.ReturnValue;
Quantity.OracleDbType = OracleDbType.Int32;
cmd.Parameters.Add(Quantity);
//now add input parameters
var TransID = cmd.Parameters.Add("trans_id", TransactionID);
TransID.Direction = ParameterDirection.Input;
TransID.OracleDbType = OracleDbType.NVarchar2;
var UsrID = cmd.Parameters.Add("usr_id", UserID);
UsrID.Direction = ParameterDirection.Input;
UsrID.OracleDbType = OracleDbType.Int32;
cmd.ExecuteNonQuery();
conn.Close();
return Convert.ToInt32(Quantity.Value);
}
The problem was in the parameter. It was null and oracle returned error. I got that if argument is null, it should be sent as DBNULL
i have written insert query for my application to create new user with password, but its not working, please check and correct it.
con.Open();
string a;
a = "insert into tbl_KKSUser(EName,Uname,Password)values(#en,#un,#pas)";
SqlCommand cm = new SqlCommand(a, con);
SqlParameter paramName;
paramName = new SqlParameter("#en", SqlDbType.VarChar, 25);
paramName.Value = DropDownList1.SelectedItem.Text;
cm.Parameters.Add(paramName);
string original = TextBox2.Text.Trim();
int h = original.GetHashCode();
string withHash = original;
b1 = Encoding.BigEndianUnicode.GetBytes(withHash);
encrypted = Convert.ToBase64String(b1);
SqlParameter paramPass;
paramPass = new SqlParameter("#pas", SqlDbType.VarChar, 300);
paramPass.Value = Convert.ToString(encrypted);
cm.Parameters.Add(paramPass);
Response.Write("<script>alert('inserted')</alert>");
con.Close();
You are not executing the query. You need to do:
cm.ExecuteNonQuery();
You must call ExecuteNonQuery function before closing connection
con.Open();
string a;
a = "insert into tbl_KKSUser(EName,Uname,Password)values(#en,#un,#pas)";
SqlCommand cm = new SqlCommand(a, con);
SqlParameter paramName;
paramName = new SqlParameter("#en", SqlDbType.VarChar, 25);
paramName.Value = DropDownList1.SelectedItem.Text;
cm.Parameters.Add(paramName);
string original = TextBox2.Text.Trim();
int h = original.GetHashCode();
string withHash = original;
b1 = Encoding.BigEndianUnicode.GetBytes(withHash);
encrypted = Convert.ToBase64String(b1);
SqlParameter paramPass;
paramPass = new SqlParameter("#pas", SqlDbType.VarChar, 300);
paramPass.Value = Convert.ToString(encrypted);
cm.Parameters.Add(paramPass);
cm.ExecuteNonQuery(); // here call ExecuteNonQuery
Response.Write("<script>alert('inserted')</alert>");
con.Close();
Two things are missing there....
You are passing 3 sql variables in the query and adding only two parameters.
add the following line too,
cm.ExecuteNonQuery();
The ExecuteNonQuery() is one of the most frequently used method in SqlCommand Object, and is used for executing statements that do not return result sets (ie. statements like insert data , update data etc.)
so use
cm.ExecuteNonQuery();
And also add all used parameters i.e. 3 parameters in your example.