多线程编程学习笔记——异步操作数据库

接上文 多线程编程学习笔记——使用异步IO

接上文 多线程编程学习笔记——编写一个异步的HTTP服务器和客户端

 

三、   异步操作数据库

本示例演示了创建数据库,异步操作数据,读取数据的过程。

1. 程序代码如下。

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; 

namespace ThreadIODemo
{

    class Program
    {

        static void Main(string[] args)
        {

            Console.WriteLine("--创建简单异步操作数据库示例 -- ");
            const string dbName = "CustomDB";

            var t = GetDBAsync(dbName);

            t.GetAwaiter().GetResult();
            Console.Read();         

        }

        static async Task GetDBAsync(string dbName)
        {

            try

            {

                const string connectionString = @"Data Source=.\SQLEXPRESS;
Initial Catalog=master;Integrated Security=SSPI
"; string outFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string dbFileName = Path.Combine(outFolder, string.Format(@"{0}.mdf", dbName)); string dbLogFileName = Path.Combine(outFolder, string.Format(@"{0}_log.ldf", dbName)); string dbConnectionString = string.Format(@"Data Source=.\SQLEXPRESS;AttachDBFileName={1};
Initial Catalog={0};Integrated Security=SSPI
", dbName, dbFileName); using (var connection = new SqlConnection(connectionString)) { await connection.OpenAsync(); if (File.Exists(dbFileName)) { Console.WriteLine("分离数据库..."); var detachCommand = new SqlCommand("sp_detach_db", connection); detachCommand.CommandType = CommandType.StoredProcedure;

detachCommand.Parameters.AddWithValue("@dbname", dbName); await detachCommand.ExecuteNonQueryAsync(); Console.WriteLine("分离数据库 成功!!"); Console.WriteLine("删除数据库文件....."); if (File.Exists(dbLogFileName)) File.Delete(dbLogFileName); File.Delete(dbFileName); Console.WriteLine("删除数据库文件成功!!"); } Console.WriteLine("创建数据库文......."); string createCommand = String.Format("Create Database {0} on
(Name=N'{0}',FILENAME='{1}')
", dbName, dbFileName); var cmd = new SqlCommand(createCommand, connection); await cmd.ExecuteNonQueryAsync(); Console.WriteLine("创建数据库成功!!"); } using (var connection = new SqlConnection(dbConnectionString)) { await connection.OpenAsync(); var cmd = new SqlCommand(" select newid()", connection); var result = await cmd.ExecuteScalarAsync(); Console.WriteLine("New GUID from database :{0}", result); cmd = new SqlCommand(@"Create Table [dbo].[CustomTable](
[ID] [int] IDENTITY(1,1) NOT NULL,[Name] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_ID] PRIMARY KEY CLUSTERED([ID] ASC) ON [PRIMARY]) ON [PRIMARY]
", connection); await cmd.ExecuteNonQueryAsync(); Console.WriteLine("创建表CustomTable成功!"); cmd = new SqlCommand(@"INSERT INTO [dbo].[CustomTable](Name) values('John') ;
INSERT INTO [dbo].[CustomTable](Name) values('张三') ;
INSERT INTO [dbo].[CustomTable](Name) values('李四') ;
INSERT INTO [dbo].[CustomTable](Name) values('王五') ;
", connection); await cmd.ExecuteNonQueryAsync(); Console.WriteLine("表CustomTable数据插入成功!"); Console.WriteLine("查询表CustomTable数据。。。。"); cmd = new SqlCommand(@" select * from [dbo].[CustomTable]", connection); using (SqlDataReader dr = await cmd.ExecuteReaderAsync()) { while (await dr.ReadAsync()) { var id = dr.GetFieldValue<int>(0); var name = dr.GetFieldValue<string>(1); Console.WriteLine("表CustomTable数据 : Id {0} ,Name {1}", id, name); } } } } catch(Exception ex) { Console.WriteLine("错误信息 : {0} ",ex.Message); } } } }

2.程序运行结果,如下。

 

 

        运行程序,如果数据库已经存在,则删除重建。当打开 连接以及单独使用OpenAsync和ExecuteNonQueryAsync方法执行SQL命令时,我们使用了I/O异步操作。

         在这个任务完成后,我们创建了一张新的表并插入了一些数据,除了之前提到的方法,我们还使用了ExceuteScalarAsync来异步地从数据库引擎中得到一个标量值,并且使用SqlDataReader.ReadAsync方法来从数据库表中异步地读取数据行。

 

posted @ 2018-02-22 14:56 DotNet菜园 阅读(...) 评论(...) 编辑 收藏