Connect to a Highly-Available SQL Server from R - sql-server

We've recently upgraded to SQL Server 2012 which is Highly-Available DR enabled. When connecting using SSMS we need to specify MultiSubnetFailover=True additional connection option + increase timeouts.
How can we replicate this in R? Without this, we observe sporadic connectivity/timeout issues.
Related, but for Python
> packageVersion('RODBC')
[1] '1.3.6'
> packageVersion('Base')
[1] '2.15.2'

If you are using a Data Source Name, you can add extra arguments to odbcConnect
odbcConnect(DSN, uid = "user_name", pwd = "password", MultiSubnetFailover = "True")
If you are using a connection string, you just need to add the arguments in your string.
odbcDriverConnect("driver=DRIVER; server=SERVER; database=DATABASE; uid=user_name; pwd=password; MultiSubnetFailover = True")

Related

Getting error while trying to connect to SQL Server Analysis Service thru ADOMD

Error:
Either the user, 'myName\user', does not have access to the 'Sample' database, or the database does not exist.
I have the Sample database in SQL Server and also sample cube in the Analysis Server, however I'm getting the error while trying to run the below code which is just for checking the connection.
AdomdConnection conn = new AdomdConnection(#"Data Source=myName\MSSQLSERVER16;Catalog=Sample");
AdomdCommand cmd = new AdomdCommand("SELECT NON EMPTY { [Measures].[Sales Count] } ON COLUMNS FROM [Sample] CELL PROPERTIES VALUE");
AdomdDataReader rdr;
int count = 0;
conn.Open();
rdr = cmd.ExecuteReader();
if (rdr.Read())
{
while (rdr.Read())
{
count++;
}
}
conn.Close();
Console.WriteLine("Count: " + count);
Is there anything wrong in my code? or, it is about the security/access issue. However, I have added the myNmae\user as server administrator at Security of Microsoft Analysis Server. May I get some help please.
I ve solved it, you need to add yourself/user in the Analysis Service thru property > security to get access the db. (also, another mistake was using the db of sql server in connection string instead of Analysis server db). Thanks!

How to connect to Local MS SQL Express Edition using Python 3

I am trying to connect to local MS SQL Express Edition. I am using canopy for Python editing.
Code:
import pymssql
conn = pymssql.connect(server='******\SQLEXPRESS',user = 'MEA\*****',password='*****',database='BSEG')
cursor = conn.cursor()
cursor.execute('SELECT * FROM Table')
print(cursor.fetchone())
conn.close()
Error::
pymssql.pyx in pymssql.connect (pymssql.c:10734)()
_mssql.pyx in _mssql.connect (_mssql.c:21821)()
_mssql.pyx in _mssql.MSSQLConnection.init (_mssql.c:5917)()
ValueError: too many values to unpack (expected 2)
user = 'MEA\*****',password='*****'
MEA\***** seems to be Windows login, in this case you shouldn't pass in any password, your user name is enough, but you also should use Integrated security or Trusted parameter in your connection string
It should be smth like this:
server='******\SQLEXPRESS',Trusted_Connection=yes,database='BSEG'

Coldfusion 9 DSN less Connection MSSQL 2008 Windows Authentication

Update:
Though the original question asked about windows authentication, any connection method would be fine. As long as it does not require creating a DSN.
I'm trying to connect my database with Windows Authentication. Here is the code.
Please advise. Thanks.
<cfscript>
classLoader = createObject("java", "java.lang.Class");
classLoader.forName("sun.jdbc.odbc.JdbcOdbcDriver");
dm = createObject("java","java.sql.DriverManager");
dburl = "jdbc:sqlserver://192.168.3.150:1433;databasename=RsDB;integratedSecurity=true";
con = dm.getConnection(dburl,"", "");
st = con.createStatement();
rs = st.ExecuteQuery("SELECT top 10 * FROM pa (nolock)");
q = createObject("java", "coldfusion.sql.QueryTable").init(rs);
</cfscript>
<cfoutput query="q">
email = #email#<br />
</cfoutput>
ERROR :
Error Occurred While Processing Request
This driver is not configured for integrated authentication.
(Ignoring your question for a moment, ... )
While it is possible to do it with a manual connection, is there a specific reason you cannot just use a standard DSN? That would be far more efficient and require a lot less code/cleanup. Not to mention that it avoids some of the common pitfalls of manual connections.
AFAIK, you can set the DSN to use windows authentication, by entering AuthenticationMethod=Type2 under "Show Advanced Settings > Connection String". Leave the "username" and "password" fields blank.
<cfquery name="qTest" datasource="YourDSN">
SELECT SYSTEM_USER AS LoginName, DB_NAME() AS DatabaseName
</cfquery>
<cfdump var="#qTest#" label="Show Connection Settings">
*NB: The DSN will use the CF Service user account, so adjust as needed
Update:
If you absolutely must use a manual connection, try using the built in driver instead of the JDBCODBC bridge. However, be sure to always close the database objects. Otherwise, open connections will start to pile up and bad things will happen.
Keep in mind, opening database connections is expensive. By not using a DSN, you lose out on the benefits of connection pooling. So overall this method will be less efficient than simply using a DSN.
<cfscript>
classLoader = createObject("java", "java.lang.Class");
classLoader.forName("macromedia.jdbc.MacromediaDriver");
dm = createObject("java","java.sql.DriverManager");
dburl = "jdbc:macromedia:sqlserver://127.0.0.1:1433;databasename=RsDB;AuthenticationMethod=Type2";
con = dm.getConnection(dburl);
st = con.createStatement();
rs = st.ExecuteQuery("SELECT getDate() AS TestValue");
q = createObject("java", "coldfusion.sql.QueryTable").init(rs);
// ALWAYS close all objects!
rs.close();
st.close();
con.close();
writeDump(q);
</cfscript>
You could also use the SQL Server JDBC Driver instead. See also Connecting with Integrated Authentication On Windows. However, that requires adding the driver jars and a DLL (sqljdbc_auth.dll) to the server, which it sounds like you cannot do.
Driver Class: com.microsoft.sqlserver.jdbc.SQLServerDriver
URL: jdbc:sqlserver://localhost:1433;integratedSecurity=true;
Found an example here that shows the username and password in the URL.
<cfset connection = driverManager
.getConnection("jdbc:mysql://localhost:3306/demodb?user=demouser&password=demopass")>
Your URL for SQL Server doesn't pass in any credentials, give that a try.

Error when connecting to MSSQL Server with Google Apps Script via JDBC

I'm trying to connect to Microsoft SQL Server using Google Apps Script. I'm using SQL Server 2008 R2 and I am using one of the suggested scripts that's supposed to read data and put it into a Spreadsheet:
https://developers.google.com/apps-script/jdbc#reading_from_a_database
The error message is:
Failed to establish a database connection. Check connection string, username, and password
Username and password are OK, the user is DBowner. The port is also correct, I tried to connect to the server via Telnet using:
o IP-address 1433
and it works.
Here's the code:
function foo() {
var conn = Jdbc.getConnection("jdbc:sqlserver://IP-adress:1433/DBName","user","password");
var stmt = conn.createStatement();
stmt.setMaxRows(100);
var start = new Date();
var rs = stmt.executeQuery("select * from person");
var doc = SpreadsheetApp.getActiveSpreadsheet();
var cell = doc.getRange('a1');
var row = 0;
while (rs.next()) {
for (var col = 0; col < rs.getMetaData().getColumnCount(); col++) {
cell.offset(row, col).setValue(rs.getString(col + 1));
}
row++;
}
rs.close();
stmt.close();
conn.close();
var end = new Date();
Logger.log("time took: " + (end.getTime() - start.getTime()));
}
Do you have any idea of what can be wrong? Do I have to make some configuration on my Server? Or in the database? The instructions mentioned above says to ensure that Google's Ip-addresses can reach the database. But instead of listing all of Google's IP-addresses I granted access to all on that port. I also enabled TCP/IP Protocol in SQL Server Configuration Manager. And I granted "Remote connections" to the Server in MSSMS. Any other idea, please?
Well, I found the answer here:
Google Apps Scripts/JDBC/MySQL
Obviously, the connection string has to look like this:
var conn = Jdbc.getConnection("jdbc:sqlserver://IP-address:1433;" + "databaseName=DBName;user=username;password=password;");
I don't understand why connection string differs from the one in Google Documentation but this one works for me...
The Issue is in the Connection string.
It should be like so
address = '%YOUR SQL HOSTNAME%';
user = '%YOUR USE%';
userPwd = '%YOUR PW%';
dbUrl = 'jdbc:sqlserver://' + address + ':1433;databaseName=' + queryDb;
var conn = Jdbc.getConnection(dbUrl, user, userPwd);
I have an entire tool on GitHub where you are able to connect to MySQL and SQL Servers. I you will be able to use it to help you. I will be constantly updating with more features overtime! You can find it here.
GOOGLE SPREADSHEET JDBC CONNECTOR TOOL

How to update recordset in VB6 using DAO connections with sql server

I am using a VB6 application. Which was using the MSAccess database. Now i am changing the database access to sql server. to getting/updating the data from MSAccess the application was using the DAO object. So now i am also trying to connect SQL Server with DAO method. Now i am able to connect the database and also able to get the data. But when i am trying to Edit record it is giving the error "Runtime error '3027' cannot update. Database or object is read only". i am showing my code here:
Public LSWs As Workspace, LSDb As Database
Dim lsConnString As String
Dim l0 As Recordset, SQL0 As String
Dim lehReturn As Integer, retrycount As Integer
lsConnString = "ODBC;DRIVER=SQL Server;SERVER=SERVERName;DATABASE=" & DBname & ";APP=Visual Basic;UID=UID;PWD=PWD"
Set LSWs = DBEngine.Workspaces(0)
Set LSDb = LSWs.OpenDatabase(DBname, dbDriverNoPrompt, True, lsConnString)
retrycount = 0
SQL0 = "select * from schedule_hdr where status = '" & Trim(PCName) & "'"
Set l0 = LSDb.OpenRecordset(SQL0, dbOpenDynaset, dbSeeChanges, adLockPessimistic)
Do While Not (l0.EOF)
LSWs.BeginTrans
l0.Edit
l0!status = "R"
l0.Update
LSWs.CommitTrans
l0.MoveNext
Loop
l0.Close
but it is giving the error at l0.Edit this line code
giving the error
"Runtime error '3027' cannot update. Database or object is read only
Any Help! or suggesion please reply
Thanks in Advance!
Initially I'm thinking that the username and password you are using for the SQL server may possibly have read-only rights.
If this is not the case and you want to stick with DAO then I suggest using the built-in ODBC link feature of Access as this helps you connect successfully to your SQL server.
However, my advice has to be abandoning DAO and going with ADO, mainly because DAO restricts your data processing to client side which is slow, and the whole point of having a dedicated server is to run as much as you can server side to dramatically improve performance.

Resources