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