Unexpected behavior when DELETEing from TABLE in SQL - c#

I have done it before, but it's not working this time.
All I'm trying to do is delete an entry from a table, and as you can see, it is supposed to output "ok" if it succeeds, (and I have manually checked the querystring data and everything matches what its trying to delete, even all the conditions are also met), but it isn't deleting.
#{
var message = "";
try
{
var d = Database.Open("tgyytuyt");
var query = "DELETE FROM Cart WHERE OrderId = '" + Request.QueryString["Value"] + "' AND UserId = '" + Request.QueryString["SubValue"] + "' AND PartNumber = '" + Request.QueryString["Final"] + "'";
d.Execute(query);
message = "ok";
//Response.Redirect("~/OSM/Default.cshtml");
}
catch(Exception ex)
{
message = ex.Message;
}
}
<p>#message</p>
Is there something that I'm doing wrong that could be causing the item to not be deleted?

The most likely cause is, that there is no row in your database which meets the conditions of your where clause.
Check that first.
But without more information about the value of your querystring and your database setup its all guessing.
It might also be a trigger...

I don't know what your execute is doing, but you should be executing a non-query. You might want to check on that.

Related

How to fix "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement.'"?

I have been getting a syntax error in my UPDATE datagridview code which happens to work in another .cs file. My group has been looking at different solutions online but everything won't work.
My group has been looking at different solutions online but everything won't seem to work.
{
connection.Open();
OleDbCommand cmd = connection.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Update Table1 set treatment = '" + treat.Text + "', remarks = '" + appRemarks.Text + "', cost = '" + treatCost.Text + "', Time = '" + textBox2.Text + "' where lastName = '" + Lastname.Text + "' ";
cmd.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Updated Successfully!");
}
The expected output should be Updated Successfully! and it should reflect in the database file after clicking the update button. Sometimes the output is "Microsoft Engine database" which does not save the changes.
The error says "System.Data.OleDb.OleDbException: 'Syntax error in UPDATE statement.'" pointing to cmd.ExecuteNonQuery();
First, never use string concatenation to build a query. You're asking for a SQL Injection attack. The biggest thing I could see here is make sure that only columns that are string columns (varchar, char, text, etc..) have single-quoted values. Is cost a number? If so then it should be:
, cost=" + treatCost.Text + ",
If cost is a number, also make sure that there isn't a currency amount in the input field. If someone puts in 1,422.00 it's not a number and will fail since , is for decoration.
If someone puts in $1422.00 it's not a number as $ is for decoration.
Either of these would fail the query.
This would happen if someone types an apostrophe into the remarks field, which SQL server will interpret as the ending quote of the string. But much worse things can happen if the user knows a bit of sql and wants to cause trouble. For example, putting '-- in the remarks will result in
Update Table1 set treatment = 'blah', remarks = ''-- where lastName = 'foobar'
which will overwrite every row in the table, not only the one containing foobar.
Use query parameters so that user-provided values can't be interpreted as query keywords and structure.
Instead of remarks = '" + appRemarks.Text + "' you will have remarks = #Remarks as well as
cmd.Parameters.Add("#Remarks", SqlDbType.NText).Value = appRemarks.Text;
and all the other user inputs likewise.

SQL query not working properly in C# while a lot of data is applied one by one

I have a problem while reading from SQL Server in C#. It is happening in SSIS, I have inserted a C# script in data flow.
I am using the code below:
using (SqlConnection connection = new SqlConnection(connectionString))
{
string vendorName = Row.VendorName.ToString().Substring(0,1).ToUpper() + Row.VendorName.ToString().Substring(1);
using (SqlCommand command = new SqlCommand("Select TOP 1 * from Logs where MessageId = '" + Row.id.ToString() + "'" +
"AND name = (Select Id from Names where vendor_name = '" + vendorName +
"order by CreatedDate desc", connection))
{
connection.Open();
string status = "";
using (SqlDataReader oReader = command.ExecuteReader())
{
while (oReader.Read())
{
status = oReader["Status"].ToString();
}
}
if (String.IsNullOrEmpty(status))
{
SaveDataToDB(Row.id, Row.VendorName, "Unknown");
}
}
}
In the Logs table, there are about 10000 rows, and the related datasource, where Row data belongs to, has around 9000 records. The problem is that, even though the query is working well, in the script it sometimes brings status value as null, because it cannot find the record in the SQL. I am getting the query and copy/pasting it to SQL, executing the query brings result there, but not in C# somehow. For example, I am running the C# two times in sequence, at the first time it says Status is null for the id: 354456, but when I run it at the second time it finds 354456 correctly but saying that status of 354499 is null.
Any idea for me to solve this issue? I really appreciate for any help.
According to me, this could be due to order of evaluation of user defined values embedded within the query. Could be the first dynamic value might be evaluated before the one in the inner query.
As I am not sure about the value to variable binding, however, I would recommend you to check following points;
a) externalise both your variable (vendor name and row id) outside and evaluate and ensure it has respective values
b) and then form your query statement with the evaluated values
May be you can debug and see the CommandText of command object just before call Execute.
your code is really inefficient, you should cache vendorname in a string and do all the substring operations on that.
for example:
string vendorName = Convert.ToString(Row.VendorName);
vendorName = vendorName.Substring(0,1).ToUpper() + vendorName.Substring(1);
instead of selecting all the columns, select the specific column for a speed up select Status from.
try to debug your code first, see which id you are getting and what is the result of your query.
its really hard to debug your code without any debug information.
change your code to this (Select Id from Names where vendor_name = '" + vendorName + "')" and put a blank space next to every " character e.g. " AND instead of "AND

Fetching data for particular Month and year

I tried Query(given below in code) But it is showing me this error
No value given for one or more required parameters.
but while debugging I am passing date as this
string monthYY = dateTimePickerMonth.Value.ToString("M-yy");
So what is the right format to check it ,how can I do it ?
Code for Query
public int GetDrID_MonthWise(string DrName,string monthYY,int refDrID)
{
int data = 0;
try
{
string sql = "Select d.DoctorID From Doctor_Master d where d.LastName + ' ' + d.FirstName = '" + DrName + "' AND Patient_registration.RegDate='" + monthYY + "' AND Patient_registration.DoctorID=" + refDrID;
cmd = new OleDbCommand(sql, acccon);
rs = cmd.ExecuteReader();
while (rs.Read())
{
data = Convert.ToInt32(rs[0]);
}
}
catch (Exception err)
{
MessageBox.Show(err.Message.ToString());
}
return data;
}
This piece of your SQL statement informs the db engine Doctor_Master is the data source:
From Doctor_Master d
However, the WHERE clause refers to 2 fields which are not present in Doctor_Master:
Patient_registration.RegDate
Patient_registration.DoctorID
I'm unsure what you actually need. My hunch is you should INNER JOIN those tables. But I think you should design and test the query in Access, leaving c# out of the picture until after you have the Access query working as you wish.
I'm not sure exactly how you are passing your parameters but you need to specify values for all three of your parameters listed
public int GetDrID_MonthWise(string DrName,string monthYY,int refDrID)

Dropdownlist data not insert in query

I select the DropDownList value to insert in query but the value remains blank in query and due to empty value in where condition not any result outcome. I do with different tricks but remain empty
if (chkBoxChanl.Checked)
{
sql += " and channelName = '" + ddlChannel.Text + "' ";
}
if (chkBoxDate.Checked)
{
sql += " and transmissionDate_ between '" + tbFrom.Text + "' and '" + tbTo.Text + "'";
}
if (chkBoxProgrm.Checked)
{
sql += " and programName ='" + ddlProgram.Text + "'";
}
if (chkBoxParty.Checked)
{
sql += " and partiesName like '%" + ddlParty.SelectedValue + "%'";
}
if (chkBoxPerson.Checked)
{
sql += " and personsName like '%" + ddlPerson.SelectedItem + "%'";
}
if (chkBoxProvince.Checked)
{
sql += " and ProvinceName like '%" + ddlProvince.SelectedItem + "%'";
}
if (chkBoxCity.Checked)
{
sql += " and CityName like '%" + ddlCity.Text + "%'";
}
Like
ddlProgram.Text
ddlProvince.SelectedItem
ddlPerson.SelectedValue
selected DropDownList value is shown empty in query.
What can I do to add the selected value in query? Please help me!
I check that when I select the dropdownist values which come on first load then 2md time after press search button dropdownlist values empty and when I press search button it first run Page_Load function and if(!IspostBack) is execute then all dropdownlist selected values become empty which cause to empty values in where clause. Now I want that when I press search button dropdownlist values remain loaded which will resolve the issue to become enpty dropdownlist values. Please guide me further
First of all: you shouldn't concatenate parameters to queries in this way. You expose yourself to SQL injection attacks.
Sorry, new to stackoverflow. Didn't see the comment button
and
programName =' mytext' OR 1 = 1;
DROP Database
Comment anything else.
You cannot concatenate your input field's values directly in your sql query. It makes your system vulnerable to Sql Injection. You should at least encode what you are retrieving from these fields before running such sql query. It is very important that you read this before going ahead.
After reading the above carefully, you can get the value of the selected item on your dropdown. You do this:
yourDropDown.SelectedItem.Value
If it does not return a value, that's probably because you didn't set any value in your dropdown. Remember to set it according to your datasource:
yourDropDown.DataValueField = "TheSourceFieldContainingTheValue";
Build your sql query something like this :
public DataSet ExecuteDataSet(string text, SqlParameter[] paramList)
{
using (SqlCommand sqlCommand = new SqlCommand(text, sqlConnection))
{
if (paramList != null)
{
foreach (var param in paramList)
{
sqlCommand.Parameters.Add(param);
}
}
SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlCommand);
DataSet dataSet=new DataSet();
dataAdapter.Fill(dataSet);
return dataSet;
}
}

SQL Update - Not updating multiple rows in a for loop

I have a DataGridView(DGV) linked to a SQlite database. I want to update some info on the DGV. So, I have a context menu that lets me change one column and update the DB as well. I want to have the ability to select multiple rows and edit as well. For ex: if i select five rows and change the type from alarms to errors ; the change is reflected in the DGV and then when i look into the database , the change isnt reflected. Only one row is updated.
My code snippet is below
foreach (DataGridViewRow r in dataGridView1.SelectedRows)
{
SQLiteTransaction SQLiteTrans = connection.BeginTransaction();
SQLiteCommand cmd = connection.CreateCommand();
MessageBox.Show(r.ToString());
if (r.Cells["typeDataGridViewTextBoxColumn"].Value.ToString().Contains("#") == false)
{
r.Cells["typeDataGridViewTextBoxColumn"].Value = r.Cells["typeDataGridViewTextBoxColumn"].Value.ToString() + " # " + max;
}
else
{
r.Cells["typeDataGridViewTextBoxColumn"].Value = r.Cells["typeDataGridViewTextBoxColumn"].Value.ToString().Substring(0, r.Cells["typeDataGridViewTextBoxColumn"].Value.ToString().IndexOf("#")) + "# " + max;
}
string querytext = "Update LogDatabase set Type = \"" + r.Cells["typeDataGridViewTextBoxColumn"].Value + "\" where HashKey = \"" + r.Cells["hashKeyDataGridViewTextBoxColumn"].Value.ToString() + "\"";
cmd.CommandText = querytext;
cmd.ExecuteNonQuery();
SQLiteTrans.Commit();
}
I dont have too much experience with SQL. So, im not sure if something is wrong with how ive updated the database!
What do i have to edit to make sure all the rows are updated in the DB as well?!
Help appreciated.
Edit: Tried checking the query before its sent.
When i try editing multiple rows in the DGV without sorting the DGV under any column it works and updates all the rows simultaneously... But When I try to sort them based on "Type" and then edit the rows, the same query is passed ! :| (Hash Key doesnt change)
Its like, the one row keeps moving up the list of rows and is always the row r in the for loop.
Edit 2: Its definitely a problem with the rows of the DGV
Everytime I sort the DGV and then try to edit the fields, the queries have hashkey values different from the once that i selected. Its like the row ids are changed completely after one update. It looks like the DGV automatically sorts once one row is updated !
Is there a way to disable this???!
It looks like you weren't increasing max counter.
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
using (SQLiteTransaction SQLiteTrans = connection.BeginTransaction())
{
SQLiteCommand cmd = connection.CreateCommand();
MessageBox.Show(row.ToString());
var txtValue = row.Cells["typeDataGridViewTextBoxColumn"].Value;
if (txtValue.Contains("#"))
{
txtValue = String.Format("{0} # {1}", txtValue, max);
}else
{
txtValue = txtValue.SubString(0, txtValue.IndexOf("#")) + "# " + max.ToString();
}
string querytext = "Update LogDatabase set Type = #type where HashKey = #key";
//Create your SqlParameters here!
cmd.CommandText = querytext;
cmd.ExecuteNonQuery();
SQLiteTrans.Commit();
max++; //You weren't increasing your counter!!
}
}
Your problem is that you are using double quotes in your SQL query to delimit your string values. Replace them for single quotes:
string querytext = "Update LogDatabase set Type = '" +
r.Cells["typeDataGridViewTextBoxColumn"].Value +
"' where HashKey = '" +
r.Cells["hashKeyDataGridViewTextBoxColumn"].Value.ToString() +
"'";
Also, beware of SQL Injection. Your code is not dealing with that.

Categories

Resources