Querying SQL Server with Google Apps Script via JDBC

前端 未结 3 1758
一生所求
一生所求 2020-12-17 06:59

I\'m using SQL Server 2008 R2 and am trying to query it using Google Apps Script. I\'m using one of the suggested scripts that\'s supposed to populate a spreadsheet but i\'m

3条回答
  •  一生所求
    2020-12-17 07:12

    I've cracked it :).... For our SQL Server and google spreadsheets at least!

    Thanks for all the help. I've been reading some of the issues here and now I'd like to share what you've helped me build. I've build a function that can take an SQL query and output the results to the spreadsheet its in.

    To get the data on the spreadsheet you'll need to open a google spreadsheet and go 'Tool' > '<> script editor'. Then past the code bellow stating with and including "/****.....". Next you will have to update these bits in the code

    var address = 'yourServerUrl:yourPortNumber';
    var user = 'yourUserName';
    var userPwd = 'yourPassword';
    var db = 'yourDatabaseName';
    

    Then you need to save it and return to the spread sheet and enter

    =SQLTOGOOGLOOGLESPREADSHEET("yourSqlQuery")
    

    Into the spreadsheet cell

    /***********************
    
    @CUSTOMFUNCTION
    
    */
    
    function SQLTOGOOGLOOGLESPREADSHEET(sqlQuery) {
        var address = 'yourServerUrl:yourPortNumber';
        var user = 'yourUserName';
        var userPwd = 'yourPassword';
        var db = 'yourDatabaseName';
        var msSqlUrlSyntax ='jdbc:sqlserver://'
    
        var dbUrl = msSqlUrlSyntax + address + ';databaseName=' + db;
    
        // msSqlUrlSyntax = 'youOptionalTestingQuery'
        var conn = Jdbc.getConnection(dbUrl, user, userPwd);
    
        var start = new Date();
        var stmt = conn.createStatement();
        stmt.setMaxRows(1000);
    
        var results = stmt.executeQuery(sqlQuery);
        var numCols = results.getMetaData().getColumnCount();
        var numRows = results.getFetchSize()
        Logger.log(numRows)
        var dataArray = [];
    
        while (results.next()) {
            var rowString = [];   
            rowString = [];
    
            for (var col = 0; col < numCols; col++)     
            {
                rowString.push(results.getString(col + 1))
            }
    
            dataArray[dataArray.length]=rowString;
        }
    
        Logger.log("dataArray =" + dataArray)
        return dataArray
    
        results.close();
        stmt.close();
    
        var end = new Date();
        Logger.log('Time elapsed: %sms', end - start);
    }
    

提交回复
热议问题