使用带有数据库连接类的参数

时间:2014-01-18 14:11:28

标签: c# sql class parameters

我正在尝试将Sql参数添加到我的项目中,但我在类中有数据库连接。我将如何添加它们,因为代码试图将employerId读作列名

我在类中有这个代码来读取和返回数据库:

public SqlDataReader ExecuteQuery(String query)        
{
    SqlCommand cmd = new SqlCommand(query,sqlConn);
    SqlDataReader reader = cmd.ExecuteReader();                
    return reader;
}

和Web服务中的代码:

[WebMethod]
public string CheckTime1(string employerId)
{
    try
    {
        UseDatabase useDb = new UseDatabase("database.mdf");
        string queryString = "SELECT * FROM [employer] WHERE [employerId] =" + employerId;
        useDb.ConnectToDatabase();

        SqlDataReader dbReader = useDb.ExecuteQuery(queryString);
        if (dbReader != null && dbReader.HasRows)
        {
            return "RECORDS EXIST";
        }
        else if (dbReader == null)
        {
            return "RECORDS DONT EXIST";
        }
        else
        {
            return "Error";
        }    
        useDb.DisconectDatabase();
    }
    catch (Exception exq)
    {
        return exq.ToString(); ;
    }
}

1 个答案:

答案 0 :(得分:0)

虽然我强烈建议您从头开始重新考虑数据访问层,但这是解决您问题的简单方法:

public SqlDataReader ExecuteQuery(String query, params object[] p)
{
    SqlCommand cmd = new SqlCommand(query, sqlConn);
    for (int i = 0; i < p.Length; i++)
    {
        cmd.Parameters.Add(new SqlParameter("@p"+i, p[i]));
    }

    SqlDataReader reader = cmd.ExecuteReader();
    return reader;
}

然后这样称呼:

public string CheckTime1(string employerId)
{
        ...

        string queryString = "SELECT * FROM [employer] WHERE [employerId] = @p0";

        SqlDataReader dbReader = useDb.ExecuteQuery(queryString, employerId);

        ...
}