Why are my parameterized queries not working in ASP.NET?

I have code that looks like this in a class that extends MemberhipProvider (the code below was a bit anonymous and simplified):

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 into cmd.ExecuteReader (); The exception is "System.Data.SqlClient.SqlException: incorrect syntax near"? "

It seems that he is behaving as if "?" in the command text is incorrectly interpreted as a parameter. I cannot understand what I am doing wrong. I admit that my ASP.NET is a little rusty, but I have written this code dozens of times, and everything I wrote above seems to match the usage patterns that I see in MSDN tutorials and examples. Can someone tell me what I am doing wrong?

.NET - 4.0. ASP.NET Visual Web Developer Express 2010. - SQL Server 2005.

+3
2

"?" , , ODBC. Sql. '@Username'.

+5

WHERE Username = ?

to

WHERE Username = @Username
+5

Source: https://habr.com/ru/post/1791335/


All Articles