C# 一个命令中有多个insert语句

C# 一个命令中有多个insert语句,c#,sql-server-2012,C#,Sql Server 2012,我在努力编写代码。当我尝试同时执行insert语句和存储过程时,存储过程的文本框值在存储到数据库时显示为空。但当我只执行存储过程时,textbox值有一个数据并存储到数据库中 我错过了什么?这是我的代码: private void recorduserlog() { sqlcon.Open(); cmd = new SqlCommand(); cmd.CommandText = "use

我在努力编写代码。当我尝试同时执行insert语句和存储过程时,存储过程的文本框值在存储到数据库时显示为空。但当我只执行存储过程时,textbox值有一个数据并存储到数据库中

我错过了什么?这是我的代码:

private void recorduserlog()
        {           
            sqlcon.Open();
            cmd = new SqlCommand();
            cmd.CommandText = "userlogs";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = sqlcon;
            cmd.Parameters.Add(new SqlParameter("@id", Main.userid));
            cmd.Parameters.Add(new SqlParameter("@fullname", Main.passname));
            cmd.Parameters.Add(new SqlParameter("@activitydetails", txtfullname.Text));
            cmd.Parameters.Add(new SqlParameter("@userform", 1));
            cmd.Parameters.Add(new SqlParameter("@datelog", DateTime.Now.ToString("M/d/yyyy hh:mm:ss")));
            cmd.ExecuteNonQuery();
            sqlcon.Close();
        }

private void btnsave_Click(object sender, EventArgs e)
    {
       if (txtusername.Text != "" && txtaccesscode.Text != "" && txtfullname.Text != "" && cmbaccessleve.Text != "")  //validating the fields whether the fields or empty or not  
            {
                if (txtaccesscode.Text.ToString().Trim().ToLower() == txtconfirm.Text.ToString().Trim().ToLower()) //validating Password textbox and confirm password textbox is match or unmatch    
                {
                    string UserName = txtusername.Text;
                    string Password = adduser.Encrypt(txtaccesscode.Text.ToString());   // Passing the Password to Encrypt method and the method will return encrypted string and stored in Password variable.  
                    SqlConnection conn = new SqlConnection(Properties.Settings.Default.myconnectionstring);
                    sqlcon.Open();
                    SqlCommand cmd2 = new SqlCommand("insert into endusers(usern,passw,fullname,accesslevel,stats)values('" + UserName + "','" + Password + "','" + txtfullname.Text + "','" + ssfapclass + "',1)", conn);
                    cmd2.ExecuteNonQuery();
                    sqlcon.Close();
                    sqlcon.Dispose();
                    MessageBox.Show("Successfully Created a User Account for '" + txtfullname.Text + "'.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                    recorduserlog();        
                }
                else
                {
                    MessageBox.Show("Access Code and Confirmation Code doesn't match!.. Please Check..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);  //showing the error message if password and confirm password doesn't match  
                }
            }
            else
            {
                MessageBox.Show("Please fill all the fields!..", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information);  //showing the error message if any fields is empty  
            }
        }
    }

还有一件事,两个SQL查询使用相同的文本框值作为参数。

我认为这将关闭应用程序

this.Close();
正如您未使用的注释中所述

SqlConnection conn = new SqlConnection(Properties.Settings.Default.myconnectionstring);

您应该使用
using
blocks

因为您要求对如何处理SqlConnection进行一些说明,所以我将尝试为您详细介绍

SqlConnection使用非托管资源(打开到数据库服务器的套接字连接)。垃圾收集器仅释放内存,而不是非托管资源。因此,当垃圾收集器从内存中删除SqlConnection时,它可能会留下悬空连接。随着时间的推移,这可能会耗尽到数据库服务器的连接数量,并导致难以诊断的问题

在.NET中,我们有一种处理非托管资源的模式。处理非托管资源的对象将实现该接口。任何可识别的对象都应小心处理。大多数情况下(有少数例外情况),IDisposable对象应该在
finally
块中处理,或者使用
语句在
中创建。这两种模式都将确保正确处置非托管资源

实现IDisposable(因为它继承自System.Data.Common.DbConnection)。因为有一个专门的类来处理数据库交互是一个好主意,这通常会给我们留下如下代码:

public class SqlServerDatabaseRepository
{
    readonly string _connectionString;

    public SqlServerDatabaseRepository(string connectionString)
    {
        _connectionString = connectionString;
    }

    public void ExecuteUserLogs(string userId, /* additional parameters */)
    {
        using(var connection = new SqlConnection(_connectionString)
        {
            //use your connection here to execute your command
        }   //here the connection falls out of scope so the using statement will handle disposing it for you
    }
}

btnsave\u单击
时,您不应该使用刚刚创建的新sqlconnection(即
conn
)而不是
sqlcon
?您的插入应该使用存储过程之类的参数,否则您将面临SQL注入攻击的风险。@xoxel i声明(sqlcon)作为公共连接,因为当我试图同时运行代码时,它会给我一个错误。所以我为insert语句和存储过程声明了两个连接。@JansenMalaggay是的,这正是因为我假设您这样做了,我要指出的是,您仍然对这两个函数使用相同的连接。至少看起来是这样。无论如何,如果您没有使用
conn
您可能应该删除它,因为您实际上从未使用过它,您不应该将SQLConction存储为字段或属性。它们应该是使用它们的方法的本地。尽可能晚地创建,尽可能早地处置。他们应该使用语句。谢谢兄弟@梅森。我想我需要做更多的阅读。。最后一个问题是,兄弟,我是要把你提供的代码包含在我的用户表单中,还是我要创建一个类?@Jansenmalagay你的表单是UI代码。他们应该不知道数据层是如何实现的。所以你需要一门新课。理想情况下,一个全新的类库(一个新项目)哇。。看来我还有很长的路要走。。我想我需要一个老师兄弟。。你能和我分享一些我能读到更多关于这个的网站吗谢谢兄弟,我非常感谢你的帮助。不,没什么特别的。你只需要找到一些好书或网络资源。但我强烈建议观看。我如何调用该类以在windows窗体命令按钮中执行查询?