3

我已经查看了与此相关的其他问题,但我遇到了不同的问题。我无法返回特定项目,它只返回我的列名。如何让商品退回?

public static string GetOneFieldRecord(string field, string companyNum)
{
    DataSet ds = new DataSet();
    SqlCommand comm = new SqlCommand();

    string strSQL = "SELECT @FieldName FROM Companies WHERE CompanyNum = @CompanyNum";
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = @connstring;
    comm.Connection = conn;
    comm.CommandText = strSQL;
    comm.Parameters.AddWithValue("@FieldName", field);
    comm.Parameters.AddWithValue("@CompanyNum", companyNum);

    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = comm;

    conn.Open();

    da.Fill(ds, "CompanyInfo");

    conn.Close();

    return ds.Tables[0].Rows[0].ItemArray[0].ToString();
}

我也试过

return ds.Tables[0].Rows[0][0].ToString();

我只是得到字段变量中的任何内容。如果我传入(“CompanyName”,33),它会返回“CompanyName”。

4

1 回答 1

3

您的查询(在 sql profiler 中)是

SELECT 'CompanyName' FROM Сompanies WHERE СompanyNum = 33

所以它准确地返回“CompanyName”字符串。您不能将列名作为 sql 参数传递。你应该做类似的事情

public static string GetOneFieldRecord(string field, string companyNum)
{
    DataSet ds = new DataSet();
    SqlCommand comm = new SqlCommand();

    string strSQL = string.Format("SELECT {0} FROM Companies WHERE CompanyNum = @CompanyNum", field);
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = @connstring;
    comm.Connection = conn;
    comm.CommandText = strSQL;
    comm.Parameters.AddWithValue("@FieldName", field);
    comm.Parameters.AddWithValue("@CompanyNum", companyNum);

    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = comm;

    conn.Open();

    da.Fill(ds, "CompanyInfo");

   conn.Close();

   return ds.Tables[0].Rows[0].ItemArray[0].ToString();
}

但是这段代码可以用于 SQL 注入。

为避免 Sql 注入,您可以检查字段变量中的 fieldName 是否为表列之一。

或者您可以获取 SELECT * FROM Сompanies WHERE СompanyNum = @CompanyNum 并从数据表中获取命名列的值:

public static string GetOneFieldRecord(string field, string companyNum)
{
    DataSet ds = new DataSet();
    SqlCommand comm = new SqlCommand();

    string strSQL = "SELECT * FROM Companies WHERE CompanyNum = @CompanyNum";
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = @connstring;
    comm.Connection = conn;
    comm.CommandText = strSQL;
    comm.Parameters.AddWithValue("@FieldName", field);
    comm.Parameters.AddWithValue("@CompanyNum", companyNum);

    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = comm;

    conn.Open();

    da.Fill(ds, "CompanyInfo");

   conn.Close();

   return ds.Tables[0].Rows[0][field].ToString();
}
于 2012-11-17T18:47:13.320 回答