简体   繁体   English

如何在向导活动步骤中执行SQL插入?

[英]How can I execute a SQL insert in a wizard active step?

On the first step of the asp:Wizard I have a login using DirectoryServices to authenticate. asp:Wizard第一步,我使用DirectoryServices登录以进行身份​​验证。 But then I want to take the UserID , Date , and the SCOPE_IDENTITY() and insert it into a table. 但是然后我想获取UserIDDateSCOPE_IDENTITY()并将其插入到表中。 Here is what I have tried. 这是我尝试过的。 When I hit next the information is not inserted but the AD function is checked properly. 当我单击下一步时,不会插入信息,但会正确检查AD功能。 I am not sure what i am doing wrong 我不确定我在做什么错

protected void OnActiveStepChanged(object sender, EventArgs e)
    {
        //check for the employee in AD
        string Domain = "mydomain.local";
        string EmployeeID = txtEmpID.Text;
        string Password = txtPassword.Text;
        string ADStatus = null;

        // If the ActiveStep is changing to Step2, check to see whether the 
        // user authenticated the AD Login Process.  If it is, skip to the Step2 step.
        if (Wizard1.ActiveStepIndex == Wizard1.WizardSteps.IndexOf(this.WizardStep2))
        {
            if (AuthenticateActiveDirectory(Domain, EmployeeID, Password) == true)
            {
                //If success ...
                ADStatus = "Success";
                Session["SessionADStatus"] = ADStatus;


                string strDepartment = ddlDepartment.SelectedValue;
                SqlConnection conn1 = new SqlConnection(ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString);
                SqlCommand cmd1 = new SqlCommand("INSERT INTO [pharm_OrderID](UserID, RequestType, CreateDate) values (@UserID, @RequestType, @CreateDate);", conn1);
                cmd1.CommandType = CommandType.Text;
                conn1.Open();

                string strUserID = txtEmpID.Text;
                cmd1.Parameters.Add("@UserID", SqlDbType.NVarChar, 50);
                cmd1.Parameters["@UserID"].Value = strUserID;

                string strRequestType = ddlReturnType.SelectedValue;
                cmd1.Parameters.Add("@ReturnType", SqlDbType.NVarChar, 50);
                cmd1.Parameters["@ReturnType"].Value = strRequestType;

                string strCreateDate = lblOrderAttemptTime.Text;
                cmd1.Parameters.Add("@CreateDate", SqlDbType.NVarChar, 50);
                cmd1.Parameters["@CreateDate"].Value = strCreateDate;

                conn1.Dispose();
                cmd1.Dispose();
                Wizard1.ActiveStepIndex = Wizard1.WizardSteps.IndexOf(this.WizardStep2);

            }
            else
            {
                ADStatus = "Failure";
                Session["SessionADStatus"] = ADStatus;
                lblADError.Visible = true;
                lblADError.Text = "Unable to authenticate Employee ID or Password.";
                Wizard1.ActiveStepIndex = Wizard1.WizardSteps.IndexOf(this.WizardStep1);
            }


        }

    }

I am not an expert of AD, but a command needs to be executed to produce any result. 我不是AD专家,但是需要执行命令才能产生任何结果。

Try to add 尝试添加

 cmd1.ExecuteNonQuery(); 

before disposing the connection and the command 在处置连接和命令之前

using(SqlConnection conn1 = new SqlConnection(........))
using(SqlCommand cmd1 = new SqlCommand("INSERT INTO [pharm_OrderID]" + 
                                      "(UserID, RequestType, CreateDate) " + 
                                      "values (@UserID, @RequestType, @CreateDate);", conn1))
{
    conn1.Open();
    string strUserID = txtEmpID.Text;
    cmd1.Parameters.Add("@UserID", SqlDbType.NVarChar, 50);
    cmd1.Parameters["@UserID"].Value = strUserID;

    string strRequestType = ddlReturnType.SelectedValue;
    cmd1.Parameters.Add("@ReturnType", SqlDbType.NVarChar, 50);
    cmd1.Parameters["@ReturnType"].Value = strRequestType;

    string strCreateDate = lblOrderAttemptTime.Text;
    cmd1.Parameters.Add("@CreateDate", SqlDbType.NVarChar, 50);
    cmd1.Parameters["@CreateDate"].Value = strCreateDate;

    cmd1.ExecuteNonQuery();
}
Wizard1.ActiveStepIndex = Wizard1.WizardSteps.IndexOf(this.WizardStep2);
...

Added also the using statement to close the connection and to dispose both command and connection. 还添加了using语句以关闭连接并同时处理命令和连接。
You should always use this pattern to correctly close the connection also in case of exceptions thrown inside the using block 您也应该始终使用此模式来正确关闭连接,以防在using块内引发异常

3 Things 3件事

  1. I agree with steve's post. 我同意史蒂夫的职务。 You should have using statements when you can over objects that need to be disposed of. 当您可以覆盖需要处理的对象时,应该使用using语句。 That way, you don't really need to remember to do it. 这样,您实际上就不必记住要这样做了。 Its handled for you. 它为您处理。
  2. the sqlcommand object has an open connection of its own. sqlcommand对象具有自己的开放连接。 Maybe using it will help resolve the issue? 也许使用它可以帮助解决问题?
  3. You really should be using the transaction object as well. 您确实也应该使用事务对象。 Transactions are basically fail safes when you enter multiple pieces of data. 当您输入多个数据时,事务基本上是故障保险柜。 For example. 例如。 Say your wizard in this case has 3 steps, and step 2 fails. 假设您的向导在这种情况下有3个步骤,而第2步失败。 You probably wouldn't want step 1 to be left over. 您可能不希望剩下步骤1。 With a transaction, you can rollback your changes on error. 通过事务,您可以回滚错误更改。

For section 2: 对于第2部分:

cmd1.Connection.Open();

instead of 代替

conn1.Open();

For Section 3: 对于第3部分:

    SqlTransaction transaction;

    // Start a local transaction.
    transaction = conn1.BeginTransaction("TheTransaction");
    cmd1.Transaction = transaction;

Then just before you dispose of your command 然后在处置命令之前

transaction.Commit();

In an error block (when you write a TryCatch, or if you detect some sort of error), you use 在错误块中(编写TryCatch或检测到某种错误时),您可以使用

transaction.Rollback();

As a note, you DO set the success status at the beginning of your sql insert. 请注意,您必须在sql插入的开头设置成功状态。 You should really be putting that after the command is successful... 命令执行成功后,您真的应该把它放进去...

Edit: In your code. 编辑:在您的代码。 You reference requesttype in your insert 您在插入中引用requesttype

new SqlCommand("INSERT INTO [pharm_OrderID](...RequestType...) values (...@RequestType...

Then later on, you use something called returntype 然后,您使用一种叫做returntype的东西

string strRequestType = ddlReturnType.SelectedValue;
cmd1.Parameters.Add("@ReturnType", SqlDbType.NVarChar, 50);
cmd1.Parameters["@ReturnType"].Value = strRequestType;

Which one is the correct one for the database. 哪一个是正确的数据库之一。 This is most likely your issue 这很可能是您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM