Click here to Skip to main content
15,881,559 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
for connecting a .mdb database from C#, how to pass a variable for selecting, e.g.:

for a string field called "a", if I directly pass a string to it, it is OK, e.g.

C#
OleDbCommand cmd = new OleDbCommand(@"SELECT * FROM mytable where a= 'hello' " , con); 


but now I want to pass a string variable str_var to it, how to do?

the following one is wrong,

C#
OleDbCommand cmd = new OleDbCommand("SELECT * FROM mytable where a = " + str_var , con);


the following one is also not correct:

C#
OleDbCommand cmd = new OleDbCommand("SELECT * FROM mytable where a = @str_var "  , con);


what would be the correct one?

thanks!
Posted
Updated 21-Jul-12 10:41am
v4
Comments
abhinavvijay 21-Jul-12 15:54pm    
when you use
OleDbCommand cmd = new OleDbCommand("SELECT * FROM mytable where a = " + str_var , con);
what error is showing?
Seraph_summer 21-Jul-12 16:02pm    
with str_var="hello", if I run OleDbDataReader reader = cmd.ExecuteReader(); then reader is null.
but if simply put directly OleDbCommand cmd = new OleDbCommand("SELECT * FROM mytable where a = 'hello' ", con); it return correct value.

1 solution

OleDbCommand cmd = new OleDbCommand("SELECT * FROM mytable where a = '" + str_var + "'" , con);


I think that's what you mean.
 
Share this answer
 
Comments
Seraph_summer 21-Jul-12 16:05pm    
great! that is what I mean. thanks a lot! this waste me a lot of time!!
it seems here is different from SqlConnection, as for SQL connection, OleDbCommand cmd = new OleDbCommand("SELECT * FROM mytable where a = @str_var " , con); should work, right?
Seraph_summer 21-Jul-12 16:08pm    
also, I am wondering why here so many quote? can you explain to me?
thanks!
R. Giskard Reventlov 21-Jul-12 17:07pm    
Firstly, you should really use a stored procedure and pass any values as pasrameters.

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