简体   繁体   中英

Dynamically calling a SQL Server stored procedure from a C# application

I have a class ( dbConnections ) with methods for handling types of DB queries. I would like to make calls to a method in this class passing the name of the procedure and an array containing the required parameters for that particular call.

However when executed, it doesn't recognise that any parameters have been passed. If I hard-code them, they work fine so there is obviously something wrong with my application of the loop.

I want to be able to re-use this method passing and getting differing parameters, I just don't know how I should be going about it. I haven't tackled the return parameters yet as I haven't got this working...

Any insight would be greatly appreciated.

This is the method in my dbConnections class:

public void ExecuteProcedure(string procedureName, string[] paramName, string[] procParams)
{
        SqlCommand cmd = new SqlCommand(procedureName, con);
        cmd.CommandType = CommandType.StoredProcedure;

        for (int i = 0; i >= paramName.Length; i++)
        {
            cmd.Parameters.AddWithValue(paramName[i], procParams[i]);
        }

        cmd.ExecuteNonQuery();
}

This is a calling method:

private void btn_logIn_Click(object sender, EventArgs e)
{          
        string uid = txb_userId.Text;
        string pwd = txb_password.Text;
        string procedureName = "spUsers_Login";
        string[] paramName = new string[2];
        string[] procParams = new string[2];

        paramName[0] = "@Username";
        procParams[0] = uid;
        paramName[1] = "@Password";
        procParams[1] = pwd;

        db.OpenConection();
        db.ExecuteProcedure(procedureName, paramName, procParams);
}

First of all check your loop

for (int i = 0; i >= paramName.Length; i++)

It will never pass the condition, it should be i<paramName.Length

Can you change the code like this

private void btn_logIn_Click(object sender, EventArgs e)
    {          
        string uid = txb_userId.Text;
        string pwd = txb_password.Text;
        string procedureName = "spUsers_Login @Username, @Password";
        string[] paramName = new string[2];
        string[] procParams = new string[2];

        paramName[0] = "@Username";
        procParams[0] = uid;
        paramName[1] = "@Password";
        procParams[1] = pwd;

        db.OpenConection();
        db.ExecuteProcedure(procedureName, paramName, procParams);
    }

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