What is wrong with this SQL query code?(C#)

B

Blue man

Hello

I think this should work , but return an error " error near ' ) " what is
wrong with this query?
I want to creat the query from 2 TextBox , save the strings into variables
and combine to make the final string command .

string namebx = Name_tbx.Text.ToString();

string personalnum=Pn_Tbx.Text.ToString();

string command="SELECT PN, FirstName, SurName, Gener FROM PersonalInfo WHERE
(FirstName =' "+namebx+" ')" + "OR (PN ="+ personalnum +" )" ;

when i try to send this command az a query the error appear! that's strange
cuz it works with one field but not with 2.
could you please tell me where is (or what is) my mistake?

thanks in advance
 
E

Emil Kvarnhammar

Hi,

The problem is that your'e missing an whitespace before
your OR.

Tip: You won't need your parantesis in your statement.
And you can write it without splitting before OR.
The command string would then look like this:

string command="SELECT PN, FirstName, SurName, Gener FROM PersonalInfo WHERE
FirstName='" + namebx + "' OR PN=" + personalnum;

or if you use string.Format it would be:

string command= string.Format("SELECT PN, FirstName, SurName, Gener FROM
PersonalInfo WHERE FirstName='{0}' OR PN={1}", namebx, personalnum);

With string.Format it's more easy to read.

regards
/Emil
 
P

Per Hornshøj-Schierbeck

Hey :)

It looks like you're missing a space after the " ')" so the string will look
like this
)OR (PN

Also you should be careful about making sql statements like that. Since you
do not replace any ' in the input strings, people could change your whole
sql statement. I always use Parameters when creating sql statements
containing strings, that way you don't have to replace the ' in the
strings....
 
B

Bob Grommes

Assuming PN is a numeric field and you're actually putting a numeric value
in it, I can't see offhand what the problem would be. However, since the
user can enter anything into namebx, you will want to guard against the
possibility of them putting an apostrophe in there (O'Malley or whatever) by
doubling any apostrophes present before you put the values into your SQL
syntax.

It is usually best in these circumstances to send the actual SQL to a file
or someplace on-screen where you can paste it into Query Analyzer and verify
the problem there and play around with it until it works, using the actual
data rather than what you think it the data is.

--Bob
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top