MS SQL无效的列名错误

时间:2016-02-23 17:34:27

标签: sql asp.net sql-server

此代码返回以下错误: “System.Data.SqlClient.SqlException(0x80131904):无效的列名'a51'”

a51是我在“企业”表的“EstablishmentCode”列中查找的记录中的正确值。帐户ID用于查找具有该帐户ID的企业表上的所有条目,并使用企业代码值填充数据集。帐户ID值来自会话变量。然后我在循环中使用这些值中的每一个,其中每个迭代在循环时调用datareader。希望我能清楚地解释清楚,但如果需要,我很乐意澄清更多。这是我的代码。

myConnection.Open();
SqlCommand getEst = new SqlCommand("SELECT EstablishmentCode FROM Establishments WHERE AccountID = " + ID, myConnection);
            da = new SqlDataAdapter(getEst);
            ds = new DataSet();
            da.Fill(ds);
            int maxrows = ds.Tables[0].Rows.Count;
            for (int x = 0; x < maxrows; x++)
            {
                getPhones = new SqlCommand("SELECT * FROM DispatcherPhones WHERE EstablishmentCode = " + ds.Tables[0].Rows[x].ItemArray.GetValue(0).ToString(), myConnection);
                myReader = getPhones.ExecuteReader();
                while (myReader.Read())
                {
                    Response.Write("<section id='phone" + myReader["Phone"].ToString() + "' style='padding:20px'>");
                    Response.Write("<section>Phone Number<br><div class='phone'>" + myReader["Phone"].ToString() + "</div></section>");
                    Response.Write("<section>Location Code<br><div class='name'>" + myReader["EstablishmentCode"].ToString() + "</div></section>");
                    Response.Write("<section>Active<br><div class='name'>" + myReader["Active"].ToString() + "</div></section>");
                    Response.Write("<section class='flex phoneButtonSection'>");
                    Response.Write("<button type=\"button\" onclick=\"showPhoneForm('" + myReader["ID"].ToString() + "');\">CHANGE</button>");
                    Response.Write("<button type=\"button\" onclick=\"deletePhones('" + myReader["ID"].ToString() + "');\">DELETE</button>");
                    Response.Write("</section>");
                    Response.Write("</section>");
                }
                myReader.Close();
            }

            myReader.Close();
            myConnection.Close();

1 个答案:

答案 0 :(得分:2)

SQL中的字符串文字用单引号(' s)表示,它们的值缺失:

getPhones = new SqlCommand
    ("SELECT * " +
     "FROM DispatcherPhones 
     "WHERE EstablishmentCode = '" + 
     // Here -------------------^ 
     ds.Tables[0].Rows[x].ItemArray.GetValue(0).ToString() +
     "'" // And here
     , myConnection);

强制性注释:为了创建SQL语句而连接字符串可能会使您的代码暴露于SQL注入攻击。您应该考虑使用预准备语句。