0

I'm having a problem showing equal results from SQL database

"select * from Log where Author=" + User.Identity.Name

That's the current command I've tried, but can't get it working.

while this works:

"select * from Log where Author='markus'"

Thanks for any help.

Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
  • 2
    You need quotes around the value User.Identity.Name in the SQL statement. – Sloan Thrasher Apr 01 '17 at 20:41
  • 1
    "select * from Log where Author='" + User.Identity.Name + "'" – Sloan Thrasher Apr 01 '17 at 20:41
  • I dont recommend doing this but try wrapping the string into single quotes: `"select * from Log where Author='" + User.Identity.Name + "'"`. Standard way of doing this is using prepared statements. – Gurwinder Singh Apr 01 '17 at 20:42
  • oh, ofcourse, thanks @SloanThrasher – Luke Remming Apr 01 '17 at 20:46
  • @GurV - what do you mean with prepared statements? I'm new to SQL – Luke Remming Apr 01 '17 at 20:48
  • @Luke - Take a look at this: http://stackoverflow.com/questions/7505808/why-do-we-always-prefer-using-parameters-in-sql-statements – Gurwinder Singh Apr 01 '17 at 20:49
  • @GurV - Thanks alot, I'll take a look at it! – Luke Remming Apr 01 '17 at 20:51
  • 1
    @LukeRemming You've heard of SQL injection, right? You don't want to be that useless coder who let it happen. This is what you are allowing with code like this. NEVER glue strings together to form sql statements unless you're 100% sure about the origin of those strings. You can write secure code very easily with [parameterized queries](http://www.dreamincode.net/forums/topic/268104-the-right-way-to-query-a-database-parameterizing-your-sql-queries/). You'd be a fool not to. Really. – spender Apr 01 '17 at 22:28

3 Answers3

0

Try the following:

"Select * from Log where Author='" + User.Identity.Name + "'" 

Actually your query is missing single quotes for name that is a string..

Muhammad Qasim
  • 1,622
  • 14
  • 26
0

You can wrap the string in single quotes like this:

"select * from Log where Author='" + User.Identity.Name + "'"

However the standard way of doing this is using parameterized statements:

"select * from Log where Author = @Author";

Then apply the value to param @Author using SqlParameter.

For more info, see:

Community
  • 1
  • 1
Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
  • DON'T DO THIS. @GurV : You should preface you answer with "This is how ***not*** to do what you want", or bring the risk of SQL injection to the forefront. People looking for quick answers won't bother following a link when they see how easily your solution "works". – spender Apr 01 '17 at 22:24
0

You can also use string.Format method for this kind of situations. Try the following.

string query=string.Format("select * from Log where Author='{0}'",User.Identity.Name)