Skip to content

Data.ExecuteNonQuery

Igor Tkachev edited this page May 20, 2016 · 1 revision

Home / Data

The ExecuteNonQuery executes an SQL statement and returns the number of rows affected.

ExecuteNonQuery.cs

using System;
using NUnit.Framework;
using BLToolkit.Data;

namespace HowTo.Data
{
    using DataAccess;

    [TestFixture]
    public class ExecuteNonQuery
    {
        [Test]
        public void Test()
        {
            Person person = new Person();

            person.FirstName = "John";
            person.LastName  = "Smith";
            person.Gender    = Gender.Male;

            using (DbManager db = new DbManager())
            {
                db.BeginTransaction();

                // Execute.
                //
                db
                    .SetSpCommand("Person_Insert", db.CreateParameters(person))
                    .ExecuteNonQuery();

                // Check the result.
                //
                person = db
                    .SetCommand(
                        "SELECT * FROM Person WHERE LastName = @lastName",
                        db.Parameter("@lastName", "Smith"))
                    .ExecuteObject<Person>();

                Assert.IsNotNull(person);

                // Cleanup.
                //
                db
                    .SetCommand(
                        "DELETE FROM Person WHERE LastName = @lastName",
                        db.Parameter("@lastName", "Smith"))
                    .ExecuteNonQuery();

                db.CommitTransaction();
            }
        }
    }
}

Person.cs

using System;

using BLToolkit.DataAccess;
using BLToolkit.Mapping;

namespace HowTo.DataAccess
{
    public class Person
    {
        [MapField("PersonID"), PrimaryKey, NonUpdatable]
        public int    ID;

        public string LastName;
        public string FirstName;
        public string MiddleName;
        public Gender Gender;
    }
}

Gender.cs

using System;

using BLToolkit.Mapping;

namespace HowTo.DataAccess
{
    public enum Gender
    {
        [MapValue("F")] Female,
        [MapValue("M")] Male,
        [MapValue("U")] Unknown,
        [MapValue("O")] Other
    }
}

App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add
            name             = "DemoConnection"
            connectionString = "Server=.;Database=BLToolkitData;Integrated Security=SSPI"
            providerName     = "System.Data.SqlClient" />
    </connectionStrings>
</configuration>
Clone this wiki locally