如何从 Azure DevOps 管道查询 Azure SQL 数据库?

How to query Azure SQL DB from Azure DevOps Pipeline?

我想从 Azure DevOps 发布管道查询 Azure SQL 数据库。如何做到这一点?

一种方法是在 Azure Devops 的 powershell 任务中使用 powershell Invoke-sqlcmd

示例:

$return = Invoke-Sqlcmd 
   -ConnectionString $DBCONNECTIONSTRING ` 
   -InputFile $PSScriptRoot/Create-DbApiUser.sql ` 
   -Variable @("password=$Password","username=$Username")

此示例使用完整的连接字符串和输入文件作为 SQL 查询。但是,您不需要它,您可以在 PowerShell 本身中编写 SQL 查询。 您还可以像示例中那样将变量传递给 SQL 查询。 此外,$return 还可以将 table 数据放入 PowerShell 变量并进一步处理它。

这也取决于你想达到什么目的。 Invoke-sqlcmd 有其局限性。

您还有一个专用的 AzureDevops 任务:

    - task: SqlAzureDacpacDeployment@1
      inputs:
        AuthenticationType: 'server'
        ServerName: '$Sqlservername'
        DatabaseName: '$Databasename'
        SqlUsername: '$Login'
        SqlPassword: '$Password'
        deployType: 'InlineSqlTask'
        SqlInline: 'SELECT * FROM foo'
        IpDetectionMethod: 'AutoDetect'

注意,要访问数据库,您必须将 sql 服务器上的防火墙 settings 设置为:

  1. 允许 Azure 服务和资源访问此服务器。
  2. 如果 1 不是一个选项,请添加一个 powershell 任务,如 documentation 中所示,以添加和删除防火墙规则,以便管道可以连接到数据库。