多線程編程學習筆記——異步操做數據庫

接上文 多線程編程學習筆記——使用異步IOhtml

接上文 多線程編程學習筆記——編寫一個異步的HTTP服務器和客戶端數據庫

 

3、   異步操做數據庫編程

本示例演示了建立數據庫,異步操做數據,讀取數據的過程。服務器

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異步操做。async

         在這個任務完成後,咱們建立了一張新的表並插入了一些數據,除了以前提到的方法,咱們還使用了ExceuteScalarAsync來異步地從數據庫引擎中獲得一個標量值,而且使用SqlDataReader.ReadAsync方法來從數據庫表中異步地讀取數據行。post

相關文章
相關標籤/搜索