SqlCommand ExecuteNonQuery Example C# VB Asp.Net

This is Example of how to use ExecuteNonQuery Method Of SqlCommand In Asp.Net Using C# And VB.

ExecuteNonQuery() Executes a Transact-SQL statement, It returns -1 for SELECT statements and Number of Rows affected for all INSERT DELETE AND UPDATE statements.

I have also explained Other methods of SqlCommand.

C# CODE
protected void btnSignIn_Click(object sender, EventArgs e)
    {
        string strConnection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
        string strInsert = "INSERT INTO Users (Username,Password) VALUES(@Username,@Password)";
        SqlConnection con = new SqlConnection(strConnection);
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = strInsert;

        SqlParameter username = new SqlParameter("@Username", SqlDbType.VarChar, 50);
        username.Value = txtUserName.Text.Trim().ToString();
        cmd.Parameters.Add(username);

        SqlParameter password = new SqlParameter("@Password", SqlDbType.VarChar, 50);
        password.Value = txtPassword.Text.Trim().ToString();
        cmd.Parameters.Add(password);

        con.Open();
        int result = cmd.ExecuteNonQuery();
       
        con.Close();
    }

VB.NET
Protected Sub btnSignIn_Click(sender As Object, e As EventArgs)
 Dim strConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
 Dim strInsert As String = "INSERT INTO Users (Username,Password) VALUES(@Username,@Password)"
 Dim con As New SqlConnection(strConnection)
 Dim cmd As New SqlCommand()
 cmd.Connection = con
 cmd.CommandType = CommandType.Text
 cmd.CommandText = strInsert

 Dim username As New SqlParameter("@Username", SqlDbType.VarChar, 50)
 username.Value = txtUserName.Text.Trim().ToString()
 cmd.Parameters.Add(username)

 Dim password As New SqlParameter("@Password", SqlDbType.VarChar, 50)
 password.Value = txtPassword.Text.Trim().ToString()
 cmd.Parameters.Add(password)

 con.Open()
 Dim result As Integer = cmd.ExecuteNonQuery()

 con.Close()
End Sub

Hope this helps

If you like this post than join us or share

Find More Articles