R connection to MS SQL - sql-server

Using R I am trying to connect to MS SQL 2014 on an Azure VM (not windows authentication)
library(RODBC)
conn <- odbcDriverConnect(connection = "Driver=SQL Server;Server=someinternetmachine.cloudapp.net;Database=MyDatabase;Uid=MyUsername;Pwd=MyPassword;")
queryResult <- sqlQuery(conn, "SELECT top 10 * FROM sometable")
With RODBC is there anywhere to do this using just a connection string (no DSN)?
Using the above I get the below errors
Warning messages:
1: In odbcDriverConnect("driver={SQL Server};server=servername\\instancename,port;database=testing;uid=abc;pwd=123456") :
[RODBC] ERROR: state 08001, code 6, message [Microsoft][ODBC SQL Server Driver][DBNETLIB]Specified SQL server not found.
2: In odbcDriverConnect("driver={SQL Server};server=servername\\instancename,port;database=testing;uid=abc;pwd=123456") :
[RODBC] ERROR: state 01000, code 11001, message [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()).
3: In odbcDriverConnect("driver={SQL Server};server=servername\\instancename,port;database=testing;uid=abc;pwd=123456") :
ODBC connection failed

Did you choose public provisioning for the VM in Azure? Additionally, you need to open the ports for SQL Server in Windows Firewall (port number depends on default or named instance). Also, in case of named instance if you are using dynamic ports then SQL Browser also needs to be opened up. More information can be found in the link here.

Managed to get this working with
driver.name <- "SQL Server"
db.name <- "master"
host.name <- "someinternetmachine.cloudapp.net"
port <- ""
server.name <- "someinternetmachine.cloudapp.net"
user.name <- "MyUsername"
pwd <- "MyPassword"
# Use a full connection string to connect
con.text <- paste("DRIVER=", driver.name,
";Database=", db.name,
";Server=", server.name,
";Port=", port,
";PROTOCOL=TCPIP",
";UID=", user.name,
";PWD=", pwd, sep = "")
con1 <- odbcDriverConnect(con.text)
res <- sqlQuery(con1, 'select * from information_schema.tables')
odbcCloseAll()

Related

Using pymssql to connect to SQL Server in Windows

Pymssql -V:2.2.1
Python -V: 3.8
DB: SQL Server 2008 R2
This is my code:
class read_sql(object):
def __init__(self):
# 服务器名
self.server = HOST_24
# 用户名
self.user = SQL_SERVER_USER
# 密码
self.password = SQL_SERVER_PASSWORD
# 数据库名
self.database = PUBMED_DB
# 连接数据库
try:
self.conn = pymssql.connect(self.server, self.user, self.password, self.database)
# 创建cursor缓冲区,用来存放sql语句
self.cursor = self.conn.cursor()
except Exception as e:
print(e)
raise ValueError('数据库链接实例化出错')
def query(self, query_str):
# 输入query_str查询语句,内容返回到cursor缓冲区内
self.cursor.execute(query_str)
# 接收全部的返回结果行.
row = self.cursor.fetchall()
return row
if __name__ == "__main__":
sql_data = read_sql()
row = sql_data.query("SELECT TOP 1 * FROM JinMo_CheckTable order by id desc")
print(row)
This is my first time connecting to SQL Server!
I get this error:
pymssql._mssql.MSSQLDatabaseException: (18456, b"\xe7\x94\xa8\xe6\x88\xb7 'sa' \xe7\x99\xbb\xe5\xbd\x95\xe5\xa4\xb1\xe8\xb4\xa5\xe3\x80\x82DB-Lib error message 20018, severity 14:
General SQL Server error: Check messages from the SQL Server
DB-Lib error message 20002, severity 9:
Adaptive Server connection failed (192.168.0.24)
DB-Lib error message 20002, severity 9:
Adaptive Server connection failed (192.168.0.24)
Please give me some suggestions - 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'

Connect to a Highly-Available SQL Server from R

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")

SQL Server ODBC connection failed

I am trying to connect SQL server using ODBC.
Could some one help interpreting what this error is and how this can be rectified?
Kindly note that there are no password issues as I use the same credentials to connect to the SQL server using Aqua studio.
dbhandle <- odbcDriverConnect('driver={SQL Server};server=SQLBBAQA;database=bbadb;uid = "aaa_bbb_ccc", pwd = "aaabbbccc123&" ')
Warning messages:
1: In odbcDriverConnect("driver={SQL Server};server=SQLBBAQA;database=bbadb;uid = \"aaa_bbb_ccc\", pwd = \"aaabbbccc123&\" ") :
[RODBC] ERROR: state 08001, code 17, message [Microsoft][ODBC SQL Server Driver][DBNETLIB]SQL Server does not exist or access denied.
2: In odbcDriverConnect("driver={SQL Server};server=SQLBBAQA;database=bbadb;uid = \"aaa_bbb_ccc\", pwd = \"aaabbbccc123&\" ") :
[RODBC] ERROR: state 01000, code 2, message [Microsoft][ODBC SQL Server Driver][DBNETLIB]ConnectionOpen (Connect()).
3: In odbcDriverConnect("driver={SQL Server};server=SQLBBAQA;database=bbadb;uid = \"aaa_bbb_ccc\", pwd = \"aaabbbccc123&\" ") :
[RODBC] ERROR: state 01S00, code 0, message [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute
4: In odbcDriverConnect("driver={SQL Server};server=SQLBBAQA;database=bbadb;uid = \"aaa_bbb_ccc\", pwd = \"aaabbbccc123&\" ") :
ODBC connection failed
I see multiple mistakes in the connection string:
server=SQLRAPQA should be in the form server=MACHINE\INSTANCE. Use server=.\SQLRAPQA if the instance is located on the same machine.
Remove all whitespaces.
Use ; as separator, not ,.
As referenced by zx8754, in RODBC odbcDriverConnect() Connection Error it is shown that a connection string should look like:
'driver={SQL Server};server=servername\\instancename,port;database=testing;uid=abc;pwd=123456' . Note the double occurences of \, this seems to be rodbc specific.

Cannot connect to Redshift database with a driver even though play.ap.db.DB can do this for the same driver

I am trying to connect to a redshift server and run some sql commands. Here is the code that I have written:
Class.forName("org.postgresql.Driver")
val url: String = s"jdbc:postgres://${user}:${password}#${host}:${port}/${database}"
val connection: Connection = DriverManager.getConnection(url, user, password)
val statement = connection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY)
val setSearchPathQuery: String = s"set search_path to '${schema}';"
statement.execute(setSearchPathQuery)
But I am getting the following error:
java.sql.SQLException: No suitable driver found for jdbc:postgres://user:password#host:port/database
But when I am using play framework's default database library with the same configuration, then I am able to connect to database successfully. Below is the configuration for the default database:
db.default.driver=org.postgresql.Driver
db.default.url="postgres://username:password#hostname:port/database"
db.default.host="hostname"
db.default.port="port"
db.default.dbname = "database"
db.default.user = "username"
db.default.password = "password"
The problem was with the url. The correct format for the url is:
jdbc:postgresql://hostname:port/database

Resources