试用 Azure Sql 数据库 (2)

以上演示了使用SSMS来管理操作数据,下面演示下使用.NET Ado.net技术操作下Azure Sql。使用Ado.net操作Azure Sql我们完全可以把Azure Sql当做SqlServer来使用。所以我们只要使用SqlServer的Data Provider来操作就可以了。

安装Dapper

为了偷懒直接使用Dapper来演示,因为Dapper本身就是基于Ado.net技术实现的。
新建一个控制台项目,使用Nuget安装Dapper。

0TiQUA.png

编写CRUD代码

我们使用Dapper来编写数据库改删查代码。数据库连接串可以在portal上点击左侧“数据库连接字符串”菜单获取。

static IDbConnection GetConnection() { var connstring = "x"; var conn = new SqlConnection(); conn.ConnectionString = connstring; return conn; } static void Main(string[] args) { using (var conn = GetConnection()) { conn.Open(); //insert var result = conn.Execute("insert into Table_1 values (@id, @name, @birthday)", new { id=0, name = "user0", birthday=DateTime.Now }); Console.WriteLine("Run insert into {0}", result>0?"success":"fail"); result = conn.Execute("insert into Table_1 values (@id, @name, @birthday)", new { id = 1, name = "user1", birthday = DateTime.Now }); Console.WriteLine("Run insert into {0}", result > 0 ? "success" : "fail"); //select var list = conn.Query<Table_1>("select * from Table_1"); foreach (var row in list) { Console.WriteLine("id:{0} name:{1} birthday:{2}", row.Id, row.Name, row.Birthday); } //update result = conn.Execute("update Table_1 set Name = @name where id = @id", new { id = 0, name = "user00" }); Console.WriteLine("Run update {0}", result > 0 ? "success" : "fail"); //delete result = conn.Execute("delete from Table_1 where id = @id", new { id = 0}); Console.WriteLine("Run delete {0}", result > 0 ? "success" : "fail"); } Console.ReadLine(); } 运行结果

写完代码我们直接F5运行一下,可以看到我们成功的使用Ado.net操作了数据。

0TQpz4.png

总结

通过以上我们简单介绍并演示了如果使用Azure Sql数据库。绝大部分时候我们可以把Azure Sql当做SqlServer来管理或者用代码操作。这为我们从本地数据库迁移到Azure Sql数据库提供了非常巨大的方便。对于应用层代码,只需要更改连接字符串就可以了。当然Azure Sql数据库跟本地Sql Server还是有一些差异的,在迁移前请先阅读文档:解析迁移到 SQL 数据库的过程中的 Transact-SQL 差异

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zzgxdz.html