Click here to Skip to main content
15,890,512 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
So I'm writing a basic CRUD application for practice as I haven't done it in a while. I came across the delete part of the CRUD application and I came across a problem. I have denoted the error line by the text "error here". Here is my code

string query = "DELETE FROM Books WHERE Title=@" + deletetitletxtbox.Text;

    using (SqlConnection conn = new SqlConnection(connString))
    using (SqlCommand command = new SqlCommand(query, conn))
        {
            conn.Open();

            command.Parameters.AddWithValue("@title", deletetitletxtbox.Text);

            command.ExecuteScalar();//error here

            conn.Close();
        }
clear();

The error I am getting is "System.Data.SqlClient.SqlException: 'Must declare the scalar variable "@The".'" So say I want to delete an column with the title of "The Main Book". That error shows up. I have been going at it for a while and have been quite annoyed at it. I apologise in advance if this is a stupid question.

What I have tried:

I have tried looking on other websites to no luck. All of the examples to me seem like they don't fit the issue that I am having. Or maybe I am looking at it wrong. At this stage it is hard to figure it out as my judgement is clouded.
Posted
Updated 15-Dec-17 13:03pm

string query = "DELETE FROM Books WHERE Title=@title";


"@title" is the parameter, and you give the @title param the relevant value here

command.Parameters.AddWithValue("@title", deletetitletxtbox.Text);


Next ExecuteScalar is for a command that returns a single column in a single row. The delete statement doesn't return anything so use ExecuteNonQuery instead, that is for when you don't expect any results back.
 
Share this answer
 
Your query is wrong. It should be
string query = "DELETE FROM Books WHERE Title=@title";

Are you using primary keys on your tables? If not, you better get into the habit of it.
 
Share this answer
 

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