[关闭]
@Ivony 2015-03-14T17:36:29.000000Z 字数 2317 阅读 1737

DbUtility

DbUtility

DbUtility is a light database access tool

How to use

execute a query

  1. db.T( "SELECT * FROM Members" ).ExecuteDataTable();

execute a query with parameter and return first row

  1. db.T( "SELECT FirstName, LastName FROM Members WHERE Username = {0}", username ).ExecuteFirstRow();

execute a query as async.

  1. await db.T( "SELECT FirstName, LastName FROM Members WHERE Username = {0}", username ).ExecuteFirstRowAsync();

Basic concept

  1. db.T( "SELECT FirstName, LastName FROM Members WHERE Username = {0}", username ).ExecuteFirstRow();

In the code above,

db is called database executor,

T( "SELECT FirstName, LastName FROM Members WHERE Username = {0}", username ) is called query definition,

and ExecuteFirstRow() is called result definition


The following code creates a database executor

  1. var db = SqlServer.FromConfiguration( "connection-string-name" );
  2. <div class="md-section-divider"></div>

Or

  1. var db = SqlServer.Connect( "connection-string" );
  2. <div class="md-section-divider"></div>

database executor is responsible for createing connection and executing queries.


A typical query definition like this below

  1. db.T( "query-text-template", params parameters );
  2. <div class="md-section-divider"></div>

The query text is SQL command to be executed. and you can use parameter placehold inside like string.Format syntax. like this below:

  1. db.T( "SELECT MemberID FROM Members WHERE Username = {0} AND Password = {1}", username, password )
  2. <div class="md-section-divider"></div>

it will create a SQL query like this below:

  1. DECLARE @Param0 AS nvarchar = 'text of username';
  2. DECLARE @Param1 AS nvarchar = 'text of password';
  3. SELECT MemberID FROM Members WHERE Username = @Param0 AND Password = @Param1;
  4. <div class="md-section-divider"></div>

the method name T means Template, so we can also write code like below:

  1. db.Template( "SELECT MemberID FROM Members WHERE Username = {0} AND Password = {1}", username, password )

and the T is an extension method, you can declare another query definition method as you like.


In the last, we talk about the result definition.
like same as the query definition, result definition are also en extension method. we have many result definition method, and all of they have asynchronous version.
the popular result definition method under this:

ExecuteNonQuery, execute query, and return the number of rows affected.

ExecuteScaler, execute query and return the first column of the first row.

ExecuteDataTable, execute query and fill a DataTable and return.

ExecuteFirstRow, execute query and return ths first row.

ExecuteEntity, execute query and return the first row to fill the specified type of entity

Get It

you can download last stable release from nuget:
DbWrench

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注