Must declare a scalar variable - c#

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.

Related

Must declare the scalar variable "#PanId"

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();

ORA-01036: illegal variable name/number for a simple query

I am facing this issue for this very simple query. I don't understand the reason behind it.
string strCon=myConnectionString;
string strSql=string.Format("select * from tblUser where UserName like '{0}%'",":Name");
OracleConnection conn = new OracleConnection(strCon);
OracleCommand command = null;
command = new OracleCommand(strSql, conn);
command.CommandType = CommandType.Text;
//Getting this value from a function it is a string type variable
val = val.Trim().ToUpper().Replace("'", "''");
command.Parameters.Add("Name", OracleType.VarChar, 80).Value = val;
DataSet dsEmail = new DataSet();
OracleDataAdapter da = new OracleDataAdapter(command);
da.Fill(dsEmail);
Finally I found a solution of my question. I had made a mistake in my query itself it was not correct. The correct syntax was
string strSql=string.Format("select * from tblUser where UserName like {0} || '%'",":Name");

ORA-06550 wrong number or types of arguments when calling Oracle stored procedure

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

C# insert query not working

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.

Problem when running SQL query

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)

Categories