Pratik.S
Pratik.S

Reputation: 470

How to make value of a column name appear with single apostrophe in sql statement of sql helper inside asp. net

 SQLHelper sqhlpr = new SQLHelper();
    sqhlpr.SqlText = "Select StudentName from tblStudentInfo where class=" + NurseryButton.Text;
    DataTable dt = sqhlpr.getDataTable(false);

This is my code.Now the result of sqhlpr.sqlText is

select StudentName from tblStudentInfo where class= **Nursery**

(i.e.NurseryButton.Text=Nursery) but the result that i want is select StudentName from tblStudentInfo where class= 'Nursery'.How can this be done??? This looks simple but I can't just figure it out...

Upvotes: 1

Views: 272

Answers (3)

Linus Caldwell
Linus Caldwell

Reputation: 11068

"Select StudentName from tblStudentInfo where class='" + NurseryButton.Text + "'";

But you definitively should not use it that way! (SQL Injection)

Here is a good answer: Sql inline query with parameters. Parameter is not read when the query is executed

Upvotes: 2

James Osborn
James Osborn

Reputation: 1275

The following code will do what you want:

SQLHelper sqhlpr = new SQLHelper();
sqhlpr.SqlText = "Select StudentName from tblStudentInfo where class = '" + NurseryButton.Text + "'";
DataTable dt = sqhlpr.getDataTable(false);

You need to think about two more things though:

  1. What happens if someone puts an apostrophe in the NurseryButton.Text somehow
  2. Will SQLHelper protect you from this sort of thing, or do you need to do it yourself

You should consider parametrized querying or stored procedures in some way to make sure that your input to the database is done safely.

Upvotes: 0

CodeCaster
CodeCaster

Reputation: 151674

Your query is a string. You do:

result = "somestring" + someVariable;

Now you want to enclose someVariable in sinlge quotes, which is done like this:

result = "somestring" + "'" + someVariable + "'";

Or shorter:

result = "somestring'" + someVariable + "'";

However is is worth noting that manually building queries is quite "not done". You should look at tools like parameterized queries or even O/R mappers like Entity Framework.

Upvotes: 0

Related Questions