3

I have code that looks like the following in a class that extends MembershipProvider (code below has been anonymized and simplified slightly):

SqlConnection conn = new SqlConnection("Integrated Security=;Persist Security Info=False;User ID=WEBUSER;Password=WEBPASSWORD;Initial Catalog=DATABASENAME;Data Source=SERVERNAME");
SqlCommand cmd = new SqlCommand("SELECT Password FROM Membership " +
    " WHERE Username = ?", conn);

cmd.Parameters.Add("@Username", System.Data.SqlDbType.NVarChar, 25).Value = "TestUser";

SqlDataReader reader = null;

try
{
    conn.Open();
    reader = cmd.ExecuteReader(); // Execution breaks here.

The code breaks when it gets to cmd.ExecuteReader(); The exception being thrown is "System.Data.SqlClient.SqlException: Incorrect syntax near '?'."

It seems to be behaving as if the "?" in the command text isn't being properly interpreted as a parameter. I can't figure out what I'm doing wrong. I admit my ASP.NET is a little rusty, but I've written code like this dozens of times before, and everything I wrote above looks like it matches the usage patterns I'm seeing in tutorials and in the MSDN examples. Can anyone tell me what I'm doing wrong?

Target .NET version is 4.0. ASP.NET is being run on my local machine inside the debugging environment in Visual Web Developer Express 2010. The database is SQL Server 2005.

1
  • Someone spent too much time using Interbase ;) Commented Feb 22, 2011 at 15:46

2 Answers 2

5

The '?' syntax, as far as I know, is ODBC syntax. Here, you're using a direct connection to Sql. Use '@Username' instead.

Sign up to request clarification or add additional context in comments.

2 Comments

Yep. That was it! Can't believe I couldn't figure that out. I guess I've generally used ODBC code before and didn't realize that what I was doing this time was different.
+1 for providing the additional explanation of WHY this is different. Kudos to you.
5

Change

WHERE Username = ?

to

WHERE Username = @Username

2 Comments

Thanks. Both the answers here were correct, super helpful, and posted at more or less the same time. But I can only accept one of them, so I accepted the other one because it explained the "why" as well as the "how".
@Joshua Carmody - I couldn't agree more. he deserved it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.