我已经查看了与此相关的其他问题,但我遇到了另一个问题。我无法获取要返回的特定项目,它只返回我的列名称。如何让物品返回?
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”。
答案 0 :(得分:3)
您的查询(在sql profiler中)是
SELECT 'CompanyName' FROM Сompanies WHERE СompanyNum = 33
因此它返回“CompanyName”字符串。您不能将列名称作为sqlparameter传递。你应该做点什么
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СompaniesWHEREompompanyNum= @CompanyNum并从datatable获取命名列的值:
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();
}