Must declare the scalar variable "#PanId" - c#

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

Related

Update table record from sqlcommand

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 = "";
}

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

Checking if id and reg already exists

I have this table Profile which has fields with user_Id and regNo and I want to check first if id and email are already exists before proceed to inserting data.
In my code, I am able to validate only one row (either id or reg number), but if I am going to validate the two of them, it gives me an error, saying "Must declare the scalar variable #userid". I don't know if it is with my select that is wrong or something in my code.
SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True");
con.Open();
SqlCommand cmdd = new SqlCommand("select * from Profile where user_Id = #userid AND RegNo = #reg", con);
SqlParameter param = new SqlParameter();
//SqlParameter param1 = new SqlParameter();
param.ParameterName = "#userid";
param.ParameterName = "#reg";
param.Value = txtid.Text;
param.Value = txtregNo.Text;
cmdd.Parameters.Add(param);
//cmdd.Parameters.Add(param1);
SqlDataReader reader = cmdd.ExecuteReader();
if (reader.HasRows)
{
MessageBox("User Id/Registry Number already exists");
}
else
{
SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True");
SqlCommand cmd = new SqlCommand("qry", con);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.AddWithValue("#id", txtid.Text);
cmd.Parameters.AddWithValue("#regno", txtregNo.Text);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
con.Open();
cmd.ExecuteNonQuery();
MessageBox("successfully saved!");
}
I am using C# with asp.net.
OK, so this isn't going to work:
SqlParameter param = new SqlParameter();
//SqlParameter param1 = new SqlParameter();
param.ParameterName = "#userid";
param.ParameterName = "#reg";
param.Value = txtid.Text;
param.Value = txtregNo.Text;
cmdd.Parameters.Add(param);
because you're reassigning the value of the same object. Change that to this:
cmdd.Parameters.AddWithValue("#userid", txtid.Text);
cmdd.Parameters.AddWithValue("#reg", txtregNo.Text);
this will add the parameters, two of them, to the SqlCommand object. Now, a little more advice, consider doing this:
using (SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True"))
{
con.Open();
using (SqlCommand cmdd = new SqlCommand("select * from Profile where user_Id = #userid AND RegNo = #reg", con))
{
...
using (SqlDataReader reader = cmdd.ExecuteReader())
{
...
}
}
}
because right now you're not disposing those object properly.
You see, anything that implements IDisposable should be wrapped in a using statement to ensure the Dispose method is called on it.
param.ParameterName = "#userid";
param.ParameterName = "#reg";
param.Value = txtid.Text;
param.Value = txtregNo.Text;
You are only declaring 1 parameter and overwriting it for both ParameterName and Value.
As an aside, you should consider looking into some type of data access helper or ORM or something to save you the trouble of all that boilerplate SQL connection code.
You are also opening another connection inside of what should already be an open SQL connection.
You are using one instance of sql parameter and passing it two different values thus overriding the first one. Try it like this:
SqlParameter param1 = new SqlParameter("#userid", txtid.Text);
SqlParameter param2 = new SqlParameter("#reg", txtregNo.Text);
Your problem as per the error is that you are reassigning the parameter to #reg after you assign it to #userid.
Try this:
SqlConnection con = new SqlConnection("Data Source=GATE-PC\\SQLEXPRESS;Initial Catalog=dbProfile;Integrated Security=True");
con.Open();
SqlCommand cmdd = new SqlCommand("select user_id from Profile where user_Id = #userid AND RegNo = #reg", con);
cmdd.Parameters.AddWithValue("#userid", txtid.Text);
cmdd.Parameters.AddWithValue("#reg", txtregNo.Text);
var id = cmdd.ExecuteReader() as string;
if (String.IsNullOrEmpty(id))
{
//Show error message and exit the method
}
else
{
//Add the row to the database if it didn't exist
}
EDIT:
I added some code to show how you could check if the userId exists in the table. Then you check against the user id itself instead of checking a reader object. Note, i am not at my dev computer right now so I did not compile this, you may have to do some tweaks but the idea is there.

Must declare a scalar variable

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.

Connection state is opened but not valid?

I have this code that I use for copy one table to another, but I got error while executing command statement.
Error says that connection is not open or valid. When I debug I can see it is opened.
Really don't know why is not valid.
con.ConnectionString = ConfigurationManager.ConnectionStrings["Con2"].ConnectionString;
con.Open();
cmd = new MySqlCommand("SELECT COUNT(*) FROM " + ConfigSettings.ReadSetting("main_base"), con);
int nRows = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
if (nRows > 0)
{
con.ConnectionString = ConfigurationManager.ConnectionStrings["Con1"].ConnectionString;
con.Open();
cmd = new MySqlCommand("INSERT INTO temp_data SELECT * FROM data");
cmd.ExecuteScalar();
}
Everything goes well until last command:
cmd = new MySqlCommand("INSERT INTO temp_data SELECT * FROM data");
cmd.ExecuteScalar();
Is this even possible if these two database are on different servers? Maybe I need to have two connections opened at the same time or something like that?
Pass the connection object to the MySqlCommand constructor:
cmd = new MySqlCommand("INSERT INTO temp_data SELECT * FROM data", con);
using (var conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["Con2"].ConnectionString))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText ="SELECT COUNT(*) FROM " + ConfigSettings.ReadSetting("main_base");
int nRows = Convert.ToInt32(cmd.ExecuteScalar());
if (nRows > 0)
{
using (var conn2 = new MySqlConnection(ConfigurationManager.ConnectionStrings["Con1"].ConnectionString))
{
conn2.Open();
using (var cmd2 = conn2.CreateCommand())
{
cmd2.CommandText ="INSERT INTO temp_data SELECT * FROM data";
cmd2.ExecuteScalar();
}
}
}
}
}

Categories