@Ivony
2015-03-14T17:36:29.000000Z
字数 2317
阅读 1737
DbUtility
DbUtility is a light database access tool
execute a query
db.T( "SELECT * FROM Members" ).ExecuteDataTable();
execute a query with parameter and return first row
db.T( "SELECT FirstName, LastName FROM Members WHERE Username = {0}", username ).ExecuteFirstRow();
execute a query as async.
await db.T( "SELECT FirstName, LastName FROM Members WHERE Username = {0}", username ).ExecuteFirstRowAsync();
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
var db = SqlServer.FromConfiguration( "connection-string-name" );
<div class="md-section-divider"></div>
Or
var db = SqlServer.Connect( "connection-string" );
<div class="md-section-divider"></div>
database executor is responsible for createing connection and executing queries.
A typical query definition like this below
db.T( "query-text-template", params parameters );
<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:
db.T( "SELECT MemberID FROM Members WHERE Username = {0} AND Password = {1}", username, password )
<div class="md-section-divider"></div>
it will create a SQL query like this below:
DECLARE @Param0 AS nvarchar = 'text of username';
DECLARE @Param1 AS nvarchar = 'text of password';
SELECT MemberID FROM Members WHERE Username = @Param0 AND Password = @Param1;
<div class="md-section-divider"></div>
the method name T means Template, so we can also write code like below:
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
you can download last stable release from nuget:
DbWrench