我在具有db_reader角色的sql server manager studio中创建了一个用户,我尝试用带有此代码的脚本连接谷歌电子表格:
function AcessaVendas () {
var URL = 'jdbc:sqlserver://servername:1433'
var USER = 'visitant'
var PASS = '*******'
var conn = Jdbc.getConnection(URL, USER, PASS);
var stmt = conn.createStatement();
stmt.setMaxRows(10000);
var start = new Date();
var rs = stmt.executeQuery( myquery());
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Dados");
ss.getRange('a2:h1000').clearContent();
var cell = ss.getRange('a2');
var row = 0;
while (rs.next()) {
for (var col = 0; col < 11; col++) {
cell.offset(row, col).setValue(rs.getString(col + 1));
}
row++;
}
rs.close();
stmt.close();
conn.close();
var end = new Date();
Logger.log('Time elapsed: ' + (end.getTime() - start.getTime()));
}
但始终显示此错误:&#34;无法建立数据库连接。检查连接字符串,用户名和密码。&#34;
我已经尝试将ip 0.0.0.0打开到255.255.255.255 有人可以告诉我哪里犯了错误?
答案 0 :(得分:1)
管理以找到正确的连接字符串。见下文:
var servername = 'servername'
var user = 'username';
var userPwd = 'password';
var db = 'dbname';
var userString = user + '@' + servername
var connectionString = 'jdbc:sqlserver://' + servername + '.database.windows.net:1433;databaseName=' + db
var conn = Jdbc.getConnection(connectionString,userString,userPwd);
我希望这会有所帮助
答案 1 :(得分:0)
此代码效果很好:连接Azure数据库并从表中获取数据
function onOpen() {
var spreadsheet = SpreadsheetApp.getActive();
var menuItems = [
{name: 'Get Data', functionName: 'readData'}
];
spreadsheet.addMenu('Report', menuItems);
}
// Replace the variables in this block with your values. Port ':1433' is not necessary
var hostName = 'SERVER.database.windows.net:1433;'
var db = 'DBNAME;';
var user = 'USER@SERVER';
var userPwd = 'PASSWORD';
var dbUrl = 'jdbc:sqlserver://'+hostName + 'databaseName='+db;
function readData() {
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
var stmt = conn.createStatement();
// Place your query below
var results = stmt.executeQuery('SELECT TOP (10) * FROM [dbo].[NAME]');
var metaData=results.getMetaData();
var numCols = metaData.getColumnCount();
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clearContents();
var arr=[];
for (var col = 0; col < numCols; col++) {
arr.push(metaData.getColumnName(col + 1));
}
sheet.appendRow(arr);
while (results.next()) {
arr=[];
for (var col = 0; col < numCols; col++) {
arr.push(results.getString(col + 1));
}
sheet.appendRow(arr);
}
results.close();
stmt.close();
sheet.autoResizeColumns(1, numCols+1);
}