简体   繁体   中英

Parameterized select query returns empty lines

I have recently started looking into SQL injection so do excuse me if I am making a obvious mistake. I have a query which returns certain fields from the database. I am trying to parameterize it now so I can avoid SQL injection. My code is below

protected string UserInfo()
{
    string UsrName = User.Identity.Name;

    using (SqlConnection connection = new SqlConnection(Common.ConnectionString))
    {
        UserDetail det = new UserDetail();

        using (SqlCommand cmd = new SqlCommand("select FirstName=@fn,LastName=@ln,MobileNumber=@mn,EmailAddress=@ea from Users,OtherInfo where OTID = USERID AND UserName=@UserName"))
        {
            cmd.Parameters.AddWithValue("UserName", UsrName); // Works correctly for this
            cmd.Parameters.AddWithValue("@fn" det.FirstName);
            cmd.Parameters.AddWithValue("@ln" det.FirstName);
            cmd.Parameters.AddWithValue("@mn" det.FirstName);
            cmd.Parameters.AddWithValue("@ea" det.FirstName);
            cmd.Connection = connection;
            connection.Open();
            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                reader.Read();
                info.FirstName = reader["FirstName"].ToString();
                info.LastName = reader["LastName"].ToString();
                info.TelNum = reader["MobileNumber"].ToString();
                info.Email = reader["EmailAddress"].ToString();
            }
        }
    }
}

My UserDetail has the following properties:

public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string TelNum { get; set; }

But it just seems to return null values? Does anyone know where I'm going wrong with this?

I think you didn't mean to pass in the empty values from your UserDetail object. You are effectively passing in the null values from UserDetail as value for the columns your query outputs.

Try to remove the parameters in the select part, remove them from the command, and try again:

using (SqlCommand cmd = new SqlCommand("select FirstName,LastName,MobileNumber,EmailAddress from Users,OtherInfo where OTID = USERID AND UserName=@UserName"))
{
    cmd.Parameters.AddWithValue("UserName", UsrName); // Works correctly for this
    cmd.Connection = connection;
    connection.Open();

    using (SqlDataReader reader = cmd.ExecuteReader())
    {
        if (reader.Read())
        {
            info.FirstName = reader["FirstName"].ToString();
            info.LastName = reader["LastName"].ToString();
            info.TelNum = reader["MobileNumber"].ToString();
            info.Email = reader["EmailAddress"].ToString();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM