Update table record from sqlcommand - c#

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

Related

Using Database Change Notification on multiple tables

I am developing an application in C# where I'm trying to use Oracle Database Change Notification.
When I'm using DCN for one table, everything is working as expected but when I am trying to use two tables, I get the following error: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt", on the line cmd.ExecuteNonQuery();
Here is the code:
string sql = "select rowid, first_name, last_name, salary from employees where employee_id = :1" +
"select country_id, country_name, region_id from countries where country_id = :2";
string constr = "User Id=hr;Password=Parola_007;Data Source=ORCL;Pooling=false";
con = new OracleConnection(constr);
con.Open();
OracleCommand cmd = new OracleCommand(sql, con);
OracleParameter p_id = new OracleParameter();
p_id.OracleDbType = OracleDbType.Decimal;
p_id.Value = 149;
OracleParameter p_id2 = new OracleParameter();
p_id2.OracleDbType = OracleDbType.Varchar2;
p_id2.Value = "BE";
cmd.BindByName = true;
cmd.Parameters.Add(p_id);
cmd.Parameters.Add(p_id2);
OracleDependency dep = new OracleDependency(cmd);
cmd.Notification.IsNotifiedOnce = false;
dep.OnChange += new OnChangeEventHandler(OnDatabaseNotification);
cmd.ExecuteNonQuery();
public static void OnDatabaseNotification(object src, OracleNotificationEventArgs args)
{
string sql = "select rowid, first_name, last_name, salary from employees where rowid = :1" +
"select rowid, country_id, country_name, region from countries where rowid = :2";
OracleParameter p_rowid = new OracleParameter();
p_rowid.Value = args.Details.Rows[0]["rowid"];
OracleParameter p_rowid2 = new OracleParameter();
p_rowid2.Value = args.Details.Rows[1]["rowid"];
OracleCommand cmd = con.CreateCommand();
cmd.CommandText = sql;
cmd.BindByName = true;
cmd.Parameters.Add(p_rowid);
cmd.Parameters.Add(p_rowid2);
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
Console.WriteLine();
Console.WriteLine("Database Change Notification received!");
DataTable changeDetails = args.Details;
Console.WriteLine("Resource {0} has changed.", changeDetails.Rows[0]["ResourceName"]);
Console.WriteLine("Resource {1} has changed.", changeDetails.Rows[1]["ResourceName"]);
dr.Dispose();
cmd.Dispose();
p_rowid.Dispose();
}
Am I doing something wrong?
Thanks.
1: you cannot do 2 sql in 1 command.
2: You can use the table trigger in oracle to check the changed table data. All changes should be logged in a table and only need to be query from that table.
sorry for my english

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

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.

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.

Categories