Database.Execute Method

Executes a non-query SQL statement.

Namespace:  WebMatrix.Data
Assembly:  WebMatrix.Data (in WebMatrix.Data.dll)

public int Execute(
	string commandText,
	params Object[] args
)

Parameters

commandText
Type: System.String
The SQL statement to execute.
args
Type: System.Object[]
(Optional) Parameters to pass to the SQL statement.

Return Value

Type: System.Int32
The count of records affected by the SQL statement.

ExceptionCondition
ArgumentException

commandText is null or empty.

The Execute method is used to perform non-query commands on a database, such as the SQL Drop, Create, Delete, Update, and Insert commands.

The following example shows how to use the Execute method to insert a record into a database table.


@{
    var connectionString = "Data Source=.\\SQLExpress;Initial Catalog=SmallBakery;Integrated Security=True";
    var providerName = "System.Data.SqlClient";

    var db = Database.OpenConnectionString(connectionString, providerName);

    var Name = Request["Name"];
    var Description = Request["Description"];
    var Price = Request["Price"];

    if (IsPost)
    {
        var insertExecuteString = "INSERT INTO Product (Name, Description, Price) VALUES (@0, @1, @2)";

        db.Execute(insertExecuteString, Name, Description, Price);

        Response.Redirect(@Href("~/ListProducts"));
    }
}

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Add Products</title>
        <style type="text/css">
            label {float:left; width: 8em; text-align: right;
                    margin-right: 0.5em;}
            fieldset {padding: 1em; border: 1px solid; width: 35em;}
            legend {padding: 2px 4px; border: 1px solid; font-weight:bold;}
        </style>
        </style>
    </head>
    <body>      
        <h1>Add New Product</h1>
        <form method="post" action="">
            <fieldset>
                <legend>Add Product</legend>
                <div>
                    <label>Name:</label>
                    <input name="Name" type="text" size="50" value="@Name" />
                </div>
                <div>
                    <label>Description:</label>
                    <input name="Description" type="text" size="50" value="@Description" />
                </div>
                <div>
                    <label>Price:</label>
                    <input name="Price" type="text" size="50" value="@Price" />
                </div>
                <div>
                    <label>&nbsp;</label>
                    <input type="submit" value="Insert" class="submit" />
                </div>
            </fieldset>
        </form>
    </body>
</html>


  • Medium trust for the immediate caller. This member can be used by partially trusted code.
Show: