Cannot use Windows authenticator in SQL statement in a form in C# Visual Studio

74 Views Asked by At

I tried to connect my windows user with a table in SQL using where as my windows user

string name = windowsIdentity.GetCurrent().Name then I put my SQL query

using (SqlCommand comm = new SqlCommand ("Select [EmployeeName] as Name from Employee where ID=" + name)

After this I just want to show in my label the name associate to the ID (which is the windows user)

using (var registro = comm.ExecuteReader())
{
    While (registro.Read())
    {
        label1.Text = registro["Name"].ToString();

When I run the code it shows this error:

System.Data.SqlClient.SqlException: 'Incorrect Syntax near ''.'

and I'm not sure how to solve this

1

There are 1 best solutions below

2
Simon Kocurek On BEST ANSWER

You want to pass in the name as a parameter: https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=dotnet-plat-ext-8.0

var comm = new SqlCommand("Select [EmployeeName] as Name from Employee where ID=@ID;");

comm.Parameters.Add("@ID", SqlDbType.NVarChar);
comm.Parameters["@ID"].Value = name;

This will likely solve any issues with possible SQL injection and passing in name as a string (surrounded with ' and with any special characters escaped).