C# delete query not working - c#

I have written this query in c# , query syntax is OK, query is also receiving parameter values as I have checked using breakpoints and also same query is working in SQL server management studio, but in visual studio it does not gives any error but also does not delete item from table.
private void deleteItem(int itemId, int saleId)
{
SqlConnection conn = new SqlConnection(connString);
SqlCommand deleteItem = new SqlCommand(
"Delete FROM items_in_sales WHERE sale_id=#sale_id AND item_id=#item_id",
conn);
deleteItem.Parameters.AddWithValue("#sale_id", itemId);
deleteItem.Parameters.AddWithValue("#item_id", saleId);
try
{
conn.Open();
deleteItem.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
please help.

Fix your parameters they are wrong way around
deleteItem.Parameters.AddWithValue("#sale_id", itemId);
deleteItem.Parameters.AddWithValue("#item_id", saleId);
should be
deleteItem.Parameters.AddWithValue("#sale_id", saleId);
deleteItem.Parameters.AddWithValue("#item_id", itemId);

Related

sqlite insert with c#

i am testing my sqlite local server with c#, I have the connection and query setup without problem. I tried to copy the query to sqlite and it runs without problem. However, when I run it in my program, nothing insert into the db. Wondering what the problem is.
I have set the db build action to Content, and the copy to output directory options to copy if newer
private void insertIntoDB(string query)
{
using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("data source=.\\VHTDatabase.db"))
{
using (System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand(conn))
{
conn.Open();
Console.WriteLine(query);
cmd.CommandText = query;
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
Try a full path to your database in your Connectionstring
Then maybe try to add the CommandText before you open the Connection.
i mean:
cmd.CommandText = query;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
Does your database give you informations with SELECT?
Maybe you need to reconfigure the User of the Database and give him rights to write, change and delete.
If nothing helps, then you can check, if it gives you an error.
try
{
cmd.CommandText = query;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex);
}

SqlCommand INSERT query does not insert data into the database

I am working on Visual Studio 2013.
In the below code the MessageBox.Show("Connected to database") is shown correctly, but the SQL query is not inserting data into the database table.
When I insert data manually then it inserts without any problems. But unfortunately the data fails to insert on the button_click command.
private void DataAdd_Load(object sender, EventArgs e)
{
try
{
conn = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=Pathname;Integrated Security=True;Connect Timeout=30");
conn.Open();
MessageBox.Show("Connected to database");
cmd = new SqlCommand("INSERT INTO datains (name, dob, gender, occupation, height, weight, relation, polexpo) values('abc', '22-Aug-2001', 'Male', 'qwe2', '23', '431', 'qw23e', 'asqwed');", conn);
}
catch (Exception e1)
{
MessageBox.Show("Connection failed");
}
}
What have I done wrong here or anything I have missed?
You have forgotten to execute the query:
cmd.ExecuteNonQuery();
It is also better to close the connection after the work is done:
conn.Close();
You have to run the ExecuteNonQuery() method of your cmd to make it work, but it's also advisable to wrap both connection and command into a using statement so that they will be disposed (the connection should be also explicitly closed)

Visual Studio and MySQL, doesn't modify any data

It seems like i do connect to my database judging by no error messege after executing the code but i'm unable to do INSERT INTO command even though it works if i copy the code to sql server command line client. What did i do wrong ?
This is my code
Maybe some code is off the bottom of the screen there but, you will need to execute the command. Something like:
cmd.ExecuteNonQuery();
Also, before doing that you should indicate that it's a text command
cmd.CommandType = System.Data.CommandType.Text;
Okay so i've actually solved it, thanks comment above for helping me at least slightly. After i posted your code it didn't work but when i moved it under the open like that :
private void Form1_Load(object sender, EventArgs e)
{
con = new MySql.Data.MySqlClient.MySqlConnection();
con.ConnectionString = myConnectionString;
MySqlCommand cmd = con.CreateCommand();
try
{
con.Open();
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
cmd.CommandText = "INSERT INTO DaneRecepcjonistki VALUES('123', 'Kot', 'Pies');";
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteNonQuery();
} It works !
Thanks !

how to delete data in Sql Server 2012 using c#?

i want to delete data in my database and using this code but its now working
private static void DeletePreviousRecord()
{
string connectionString = "Data Source=ABDULLAH\\ABDULLAHZAFAR;Initial Catalog=FoodHunt;Integrated Security=True";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("Delete From RestaurantsMenu", con))
{
try
{
cmd.CommandType = CommandType.StoredProcedure;
con.Open();
var result = cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{ }
}
}
}
i tried this but this is not working, how can i do that, any suggestion?
Setting the CommandType to StoredProcedure when you clearly use a sql text directly cannot do any good at your code.
Remove that line because the default is CommandType.Text (and this is correct for your command)
But as stated in the comment above.
If you catch the exception, at least write in some log or display at
video what the error message is
If you don't add a WHERE clause at your sql statement, you delete
everything in the table (Probably you are lucky that this code has
not worked)
Looking at your comment below, if you want to delete every record (and reset the Identity column if any) a faster approach is
using (SqlCommand cmd = new SqlCommand("TRUNCATE TABLE RestaurantsMenu", con))
For a quick reading about the difference between TRUNCATE and DELETE look at this article

Why it doesn't insert into sql table?

This is my code for insert into a table. It doesn't get any error, but it doesn't insert to the table. I tried by using stored_procedure too but it doesn't insert too. I can't find what I'm doing wrong.
private void btnSave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = Properties.Settings.Default.bm_DatabaseConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
//cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "INSERT INTO [tbl_Buildings] (buildingName,buildingImage,buildingAddress,floorNo,apartsNo, buildingDesc) VALUES (#builName,#builImage,#builAddr,#floorNo,#apartsNo,#builDesc)";//"prc_AddNewBuilding";
cmd.Parameters.Add("#builName", txtBuildingName.Text);
cmd.Parameters.Add("#builAddr", txtAddress.Text);
cmd.Parameters.Add("#builImage", "Undefined");
cmd.Parameters.Add("#floorNo", (int)numFloorNo.Value);
cmd.Parameters.Add("#apartsNo", (int)numApartsNo.Value);
cmd.Parameters.Add("#builDesc", txtBuilDesc.Text);
try
{
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("New building has been added successfully");
this.Close();
}
catch (SqlException sqlex)
{
MessageBox.Show(sqlex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
I am using VS2012. What could I be doing wrong?
Try using:
Database.Command.Parameters.AddWithValue("#variableName", variable)
The only thing I could imagine why your values won't be inserted into your DB is a SQL Exception. Maybe you're missing some quotes?
Alternatiely use the complete "Add" Statement like this:
Database.Command.Parameters.Add(item, System.Data.SqlDbType.VarChar).Direction = ParameterDirection.Input
Item in this case is your variable containing the data you want to store
EDIT
My original answer assumed SQL Server was the database. As it turns out, the OP is using MS Access. Seems, based on other evidence, the file path for the .mdb file was the culprit, not the C# or SQL.
My original answer:
Using the connection string...
Server=myhost;Database=testdatatbase;Trusted_Connection=True;
the code you provided above works. I went to SQL Enterprise Manager, created a table named dbo.tbl_Buildings with the following attributes...
buildingName = nvarchar(50)
buildingImage = nvarchar(50)
buildingAddress = nvarchar(50)
floorNo = int
apartsNo = int
buildingDesc = nvarchar(50)
I then passed in dummy values, then ran the following query...
select * from testdatatbase.dbo.tbl_Buildings
and it shows the record....
-- seems to work for me...
(Maybe check your datatypes - make sure your table types match your types in the code)

Categories