Search code examples
rubyazureazure-cosmosdbjruby

How to connect to cosmos db in ruby file


I want to connect to Azure cosmos DB in ruby file, Please can anyone suggest how can I connect with the DB , is there any gem available, to which I can pass connection string of that DB .

Thanks


Solution

  • The following info worked for me, I found it here Connect to CosmosDB using RUBY

    If you have not already, first specify connection properties in an ODBC DSN (data source name). This is the last step of the driver installation. You can use the Microsoft ODBC Data Source Administrator to create and configure ODBC DSNs.

    You need the following info from CosmosDB

    AccountEndpoint: The Cosmos DB account URL from the Keys blade of the Cosmos DB account AccountKey: In the Azure portal, navigate to the Cosmos DB service and select your Azure Cosmos DB account. From the resource menu, go to the Keys page. Find the PRIMARY KEY value and set AccountKey to this value.

    you will need to install the following gems

    gem install dbi
    gem install dbd-odbc
    gem install ruby-odbc
    

    The write something like this

    #connect to the DSN
    require 'DBI'
    cnxn = DBI.connect('DBI:ODBC:CData CosmosDB Source','','')
    
    #execute a SELECT query and store the result set
    resultSet = cnxn.execute("SELECT City, CompanyName FROM Customers")
    
    #display the names of the columns
    resultSet.column_names.each do |name|
      print name, "\t"
    end
    puts
    
    #display the results
    while row = resultSet.fetch do
      (0..resultSet.column_names.size - 1).each do |n|
        print row[n], "\t"
      end
      puts
    end
    resultSet.finish
    
    #close the connection
    cnxn.disconnect if cnxn