SQL Delete query not working properly - c#

I had a logic error in my sql delete query which would not give any error in visual studio and did not delete the record in the database
Here is a snippet of my code
SqlCommand cmd = new SqlCommand(
#"DELETE FROM table_name
WHERE item_id=" + itmIDs +
" AND vendor_id=" + vendIDs +
" AND dozen=" + selectedItmDzn +
" AND quantity=" + selectedItmQty +
" AND total_price=" + selectedItmTotPrc + "",
con);
cmd.ExecuteNonQuery();
here is my conString
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=InvenotyBB;Integrated Security=SSPI")
I have confirmed that the other verbs (select, update, etc) work, just not the specific command for delete.

I can almost guarantee your connection string has:
User Instance=true;AttachDbFileName=|Data Directory|...something.mdf;
If this is the case, STOP DOING THAT. The AttachDbFileName feature actually creates a copy of your database file. So the one you have open in Management Studio or Visual Studio is different from the one your application created via the connection string. Your application deletes from the copy, there are no exceptions (because it worked), you refresh the original, and it looks like it didn't work.
See the answer from #marc_s's here:
https://stackoverflow.com/a/7222952/61305
If this isn't it, then I suspect either (a) errors are being ignored due to try/catch somewhere, or (b) your method for checking if the command worked is suspect. For example, if you are relying on a count, and the where clause matches zero rows, then the command worked but it didn't delete anything, therefore the count remains the same.
If neither of those are true, then goto line 1 of my answer. There is no magic here, a delete command will either affect 0 or more rows, or it will return an exception. Anything else can only be explained by improper troubleshooting / debugging.

Given this original code (via my formatting):
SqlCommand cmd = new SqlCommand(
#"DELETE FROM table_name
WHERE item_id=" + itmIDs +
" AND vendor_id=" + vendIDs +
" AND dozen=" + selectedItmDzn +
" AND quantity=" + selectedItmQty +
" AND total_price=" + selectedItmTotPrc + "",
con);
cmd.ExecuteNonQuery();
Let's change this to:
string deleteQuery =
#"DELETE FROM table_name
WHERE item_id=" + itmIDs +
" AND vendor_id=" + vendIDs +
" AND dozen=" + selectedItmDzn +
" AND quantity=" + selectedItmQty +
" AND total_price=" + selectedItmTotPrc + "";
SqlCommand cmd = new SqlCommand(deleteQuery, con); /* set a breakpoint here */
cmd.ExecuteNonQuery();
Set the breakpoint and copy-paste that query to a comment here so we can see it.

Related

How do I make a foreign key in one of my databases copy the primary key that it is referencing to while I create a record? [duplicate]

I have a query to insert a row into a table, which has a field called ID, which is populated using an AUTO_INCREMENT on the column. I need to get this value for the next bit of functionality, but when I run the following, it always returns 0 even though the actual value is not 0:
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', " + bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID + ")";
int id = Convert.ToInt32(comm.ExecuteScalar());
According to my understanding, this should return the ID column, but it just returns 0 every time. Any ideas?
EDIT:
When I run:
"INSERT INTO INVOICE (INVOICE_DATE, BOOK_FEE, ADMIN_FEE, TOTAL_FEE, CUSTOMER_ID) VALUES ('2009:01:01 10:21:12', 50, 7, 57, 2134);last_insert_id();"
I get:
{"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'last_insert_id()' at line 1"}
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertStatement; // Set the insert statement
comm.ExecuteNonQuery(); // Execute the command
long id = comm.LastInsertedId; // Get the ID of the inserted item
[Edit: added "select" before references to last_insert_id()]
What about running "select last_insert_id();" after your insert?
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', "
+ bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID + ");";
+ "select last_insert_id();"
int id = Convert.ToInt32(comm.ExecuteScalar());
Edit: As duffymo mentioned, you really would be well served using parameterized queries like this.
Edit: Until you switch over to a parameterized version, you might find peace with string.Format:
comm.CommandText = string.Format("{0} '{1}', {2}, {3}, {4}, {5}); select last_insert_id();",
insertInvoice, invoiceDate.ToString(...), bookFee, adminFee, totalFee, customerID);
Use LastInsertedId.
View my suggestion with example here: http://livshitz.wordpress.com/2011/10/28/returning-last-inserted-id-in-c-using-mysql-db-provider/
It bothers me to see anybody taking a Date and storing it in a database as a String. Why not have the column type reflect reality?
I'm also surprised to see a SQL query being built up using string concatenation. I'm a Java developer, and I don't know C# at all, but I'd wonder if there wasn't a binding mechanism along the lines of java.sql.PreparedStatement somewhere in the library? It's recommended for guarding against SQL injection attacks. Another benefit is possible performance benefits, because the SQL can be parsed, verified, cached once, and reused.
Actually, the ExecuteScalar method returns the first column of the first row of the DataSet being returned. In your case, you're only doing an Insert, you're not actually querying any data. You need to query the scope_identity() after you're insert (that's the syntax for SQL Server) and then you'll have your answer. See here:
Linkage
EDIT: As Michael Haren pointed out, you mentioned in your tag you're using MySql, use last_insert_id(); instead of scope_identity();

Is it possible to update data without actually removing the previously added data in MySQL?

Im tasked to update selected information however not delete the previous data added...How do I update without replacing the old data and is it possible to view it if necessary?
Heres a part of my code:
MySqlConnection conn = new MySqlConnection(mycon);
string Query = "update mydb.client set clientLN='" + txtClientLName.Text + "', clientFN='" + txtClientFName.Text + "', clientMN='" + txtClientMName.Text + "', clientType='" + cmbTypeMembership.Text + "', clientMembershipType='" + cmbRates.Text + "', clientMembershipValidity='" + Days.ToString() + "', clientMembershipStatus='" + validity + "' where clientID='" + clientID + "';";
conn.Open();
MySqlCommand myCommand = new MySqlCommand(Query, conn);
myReader = myCommand.ExecuteReader();
conn.Close();
MessageBox.Show("Client Successfully Renewed!");
In sql, an update without replacing old data is called an insert
It sounds like you need to keep the old values related to the client around for [backup, audit, some other reason]. Two possible approaches;
1) Keep a archive table where you insert the existing record (with a timestamp) before issuing the update.
2) Make you main table effective-dated (but your application will need to know how to deal w/ effective-dated records).

Update in SQL query doesn't work c#

I want to update data in my SQL Server table, this code here works fine in my other project but when I copied it to other project it doesn't work anymore.
Here's my code:
con.Open();
float prc = float.Parse(textBox4.Text);
int sum = int.Parse(textBox3.Text);
string sql = "UPDATE LIB_INVENTORY set PRICE=(" + prc + "), QUANTITY=([QUANTITY]) +
(" + sum + "), BSTATUS='" + textBox5.Text + "' where BOOKNAME='"
+ textBox1.Text + "' and PUBLISHER='" + textBox2.Text + "'";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("One item updated updated!");
It runs successfully but when I checked the table no data has been successfully updated. I checked my code but it is really the same as my other project that works fine. Can somebody help me?
if no error is there then it means where clause is not fulfilling. i think your has typed like :
where BOOKNAME='"<spaace>+ textBox1.Text+<spaace>"' and PUBLISHER='"<spaace>+ textBox2.Text +<spaace>"'";
so just erase space and
try this out.
string sql = "UPDATE LIB_INVENTORY set PRICE=("+prc+"), QUANTITY= ([QUANTITY]) + ("+sum+"), BSTATUS='"+textBox5.Text+"' where BOOKNAME='"+textBox1.Text+"' and PUBLISHER='"+textBox2.Text+"'";
as suggested you should really use parameters for your sql query. On top of this do the following :
SqlCommand cmd = new SqlCommand(sql, con);
int nbrUpdates = cmd.ExecuteNonQuery();
con.Close();
if (nbrUpdates>0) MessageBox.Show("One item updated updated!");
else MessageBox.Show(sql);
You can then check if the string in the sql is correct.
Also log in to your database manually and check if the data you want to update is in fact there.
If it is and the update still does not work, make your code do a select statement for the data you want to update. You still might be accessing the wrong database.
Now to start using sql with parameters like you are supposed to read this :
http://www.csharp-station.com/Tutorial/AdoDotNet/lesson06

ExecuteNonquery returns 0

In my c# application i am trying to delete a record and i am returning result of the executenonquery to check the deletion is exactly happening as below.
rowsAffected = db.ExecuteNonQuerySQL(
#"DELETE FROM relation WHERE parent_itemid = " + SourceThingId + " AND " +
" child_itemid = " + ThingId + " AND " +
" relation_typeid = " + RelationTypeId);
And the executenonquery is definesd as below,
using (SQLiteTransaction dbtrans = conn.BeginTransaction())
{
SQLiteCommand cmd = conn.CreateCommand();
cmd.CommandText = sqlExpr;
cmd.CommandType = CommandType.Text;
ireturn = cmd.ExecuteNonQuery();
dbtrans.Commit();
}
return ireturn;
But when i am executing its not deleting and the value returns 0.The databse used is sqlite.
Do any one have idea why it happens.Please help.
Thanx in advance.
Well it certainly sounds like the record simply isn't there. You should debug this by running a SELECT * with the same query, and see whether you get any results back.
You should also stop putting your values directly into SQL, and instead use parameterized SQL. That will give a better separation of code and data, avoid SQL injection attacks, and avoid conversion issues (particularly with date/time values).

Update textbox value into sql

When im trying to update the textbox values into db.It throws me an exception "Invalid syntax near (value of the txtkey.text)" Can anyone Help
SqlConnection con = new SqlConnection("server=server1;Database=testdb;User Id=dev;password=sqlad#2006");
SqlCommand com = new SqlCommand("insert into tbl_licensing(UserName,CompanyName,EmailId,LicenseKey) values ('" + txtUserName.Text + "','" + txtCompanyName.Text + "','" + txtEmailId.Text + "','"+ txtKey.Text + "'",con);
con.Open();
com.ExecuteNonQuery();
con.Close();
You have started this "values (" but you never closed it. Check again.
It will be good if you use parameterized query or stored procedure instead of directly writing query
You can check this article.
http://www.aspnet101.com/2007/03/parameterized-queries-in-asp-net/
You have forgotten closing bracket ) in your query
Updated code for you :
SqlCommand com = new SqlCommand("insert into
tbl_licensing(UserName,CompanyName,EmailId,LicenseKey) values ('" + txtUserName.Text + "','"
+ txtCompanyName.Text + "','" + txtEmailId.Text + "','"+ txtKey.Text + "')",con);
Your code is wrong in many ways. Use parameterized query and you will
Avoid sql injection attacks
You will
not have to escape the data entered
by user
The performance of your
queries will get better
The code will be much easier to read, understand and refactor.
The correct way to use SqlCommand with parameters is to fill the SqlCommand's Parameters collection with parameter names and values.
See MSDN documentation.

Categories