Click here to Skip to main content
15,885,365 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i am tyring to put a query to be perfoming the database CRUD using c# and access database but am failing to put the code in a method so that i should not repeate it.

What I have tried:

public String DeleteItem(int UserInput, String WhichTable)
        {
            String Item;
            OleDbConnection connection = new OleDbConnection();
            connection.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|Rental_database .accdb");<pre lang="C#"><pre lang="C#">

connection.Open();
Item = "delete from '"+WhichTable+"' Where ID= "+ UserInput +" ";
OleDbCommand command = new OleDbCommand(Item, connection);
command.ExecuteNonQuery();
return Item;
Posted
Updated 10-Jan-23 19:33pm

First off, you never close the connection, which is bad - use a using block to ensure that connections and commands are closed and disposed when you are finished with them:
C#
using (SqlConnection con = new SqlConnection(strConnect))
    {
    con.Open();
    using (SqlCommand cmd = new SqlCommand("SELECT Age, Description FROM myTable WHERE ID = @ID", con))
        {
        cmd.Parameters.AddWithValue("@ID", myTextBox.Text);
        using (SqlDataReader reader = cmd.ExecuteReader())
            {
            while (reader.Read())
                {
                int age = (int) reader["Age"];
                string desc = (string) reader["Description"];
                Console.WriteLine($"{age}\n{desc}");
                }
            }
        }
    }
(It's the same for OleDb objects as SqlServer objects).

Second, why are you returning an SQL query? Wouldn't it make more sense to return the result of the ExecuteNonQuery call? That way, the calling function can check if it deleted any rows ...

Third, that code looks like it might work - though I'd worry about SQL Injection
 
Share this answer
 
I think that you're looking for this:
C#
String delQuery = $"DELETE FROM {WhichTable} WHERE [ID]= ?";

OleDbCommand delcmd = new OleDbCommand();

delcmd.CommandText = delQuery;
delcmd.Connection = connection ;
delcmd.Parameters.AddWithValue("?", UserInput);

delcmd.ExecuteNonQuery();

You should never put values into the query string. Doing so opens you to SQL injection attacks[^].
 
Share this answer
 
Comments
BillWoodruff 13-Jan-23 0:45am    
did you actually run this code and verify it works ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900