I'm new at pyodbc and I'm using the following code to connect my database:
(IDE is VS Code) I'm testing the connection to ensure that an error message is displayed if I fail to connect to the server:
All is fine if the server name is correct, but if I deliberately misspell the server name in order to prove that the connection is not successful, then the code appears to hang. (VSC shows code still running and I need to manually click on Stop), so then I don't appear to reach the try/except statement.
import pyodbc
try:
conn = pyodbc.connect(Trusted_Connection='yes', driver = '{SQL Server}',server = 'xxx-xxxx\SQLEXPRESS' , database = 'master')
except pyodbc.Error as ex:
print(ex)
else:
print('Connected')
print('Done')
Thanks all
Russ
Related
I have a MongoDB database I have storing a large dataset. I am trying to import my database into MATLAB to perform data visualization, but am getting strange errors that I have not been able to debug in doing so. I have my database running using mongod on localhost on port 27017.
I do have the Database Toolbox add on for MATLAB, and the MongoDB specific one as well.
Following the example of the MATLAB documentation, I created variables:
server = "0.0.0.0" (I have also tried putting localhost here)
port = 27017
dbname = "NYPDData"
conn = mongo(server, port, dbname)
When I do so, I recieve the error that:
Error using error
Unable to load a message catalog 'mongodb:mongodb'. Please check
the file location and format.
Error in mongo (line 389)
error(message('mongodb:mongodb:DriverError',mongo.extractExceptionMessage(e)));
When I try simple running conn = mongo() with any parameters however, it seems to work, and returns:
conn =
mongo with properties:
Database: ''
UserName: ''
Server: {}
Port:
CollectionNames: {}
TotalDocuments:
If you have any insight on how to solve this error, please let me know. Thank you!
Type this before calling the mongo function : registerrealtimecataloglocation('c:\ProgramData\MATLAB\SupportPackages\R2017b')
It should return 1 if everything goes well. Don't forget to change the previous line by your number of version (R2017b here) with yours.
And then it should find the message in the catalog.
I'm trying to connect to the SQL Sever database using R but not sure on the details for the query string. I normally use SQL server management studio on SQL Server 2008 and connnect using single sign on. I found the below example
myconn <- odbcDriverConnect(connection="Driver={SQL Server
Native Client 11.0};server=hostname;database=TPCH;
trusted_connection=yes;")
I get the below warning message
Warning messages:
1: In odbcDriverConnect(connection = "Driver={SQL Server \nNative Client 11.0};server=hostname;database=TPCH;\ntrusted_connection=yes;") :
[RODBC] ERROR: state IM002, code 0, message [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
2: In odbcDriverConnect(connection = "Driver={SQL Server \nNative Client 11.0};server=hostname;database=TPCH;\ntrusted_connection=yes;") :
ODBC connection failed
How do I go about finding the specifics i need?
I have done this in the past with an odbc named connection that I've already had in place. In case you don't know, you can create one in windows by typing into the search prompt 'odbc' and selecting "set up data sources". For example - if you named an odbc connection 'con1' you can connect the following way:
con<-odbcConnect('con1') #opening odbc connection
df<-sqlQuery(con, "select *
from ssiD.dbo.HOURLY_SALES
") #querying table
close(con)
This works for me.
library(RODBC)
dbconnection <- odbcDriverConnect("Driver=ODBC Driver 11 for SQL Server;Server=server_name; Database=table_name;Uid=; Pwd=; trusted_connection=yes")
initdata <- sqlQuery(dbconnection,paste("select * from MyTable;"))
odbcClose(channel)
Also, see these links.
RODBC odbcDriverConnect() Connection Error
https://www.simple-talk.com/sql/reporting-services/making-data-analytics-simpler-sql-server-and-r/
The problem is simpler than this. The big clue is the \n in the error message. Something has re-flowed your connection string such that there is now a new-line character in the driver name. That won't match any registered driver name. Pain and suffering then ensues. Make sure your whole connection string is on a single line!
I often use:
driver={SQL Server Native Client 11.0}; ...
and it works really well. Much better than having to rely on pre-defined connection names.
Try another ODBC driver.
In windows press the "windows" button and then type "odbc".
Click the "Data sources (ODBC)" link.
Go to the "Drivers" tab to see the available drivers for SQL Server.
Also - remove the " " spaces after the semicolons in your connection string.
Note - the database property should point to a database name rather than a table name.
This worked for me:
odbcDriverConnect("Driver=SQL Server Native Client 11.0;Server=<IP of server>;Database=<Database Name>;Uid=<SQL username>;Pwd=<SQL password>")
First, you need to install the package 'RSQLServer', and all its dependencies.
Then execute the following command in RStudio, with relevant parameters:
conn <- DBI::dbConnect(RSQLServer::SQLServer(),
server = '<server>',
port = '<port>',
properties = list(
user = '<user>',
password = '<password>'
))
Finally, db_list_tables(conn) gives you the list of tables in the corresponding database.
I've spent the last day or two setting up unixODBC and freetds on ubuntu 12 - not a fun process in itself but it does now work using both sqsh and isql. I've installed node-odbc and I'm using the code snippet provided in the github readme to test the connection but I always get
S1000:1:0:[unixODBC][FreeTDS][SQL Server]Unable to connect to data source
WARNING: ev_unref is deprecated, use uv_unref
[Error: Error opening database]
Using isql I run isql -v SERVER user pass (using the correct creds..) and then use DATABASE once connected and it all works and I can run queries fine. My connection string in the js is
"DRIVER={FreeTDS};SERVER=SERVER;UID=user;PWD=pass;DATABASE=DATABASE"
Which exactly matches the credentials used for connecting with isql but in Node I get the aforementioned error. Any ideas on why this is happening? Is it possible that it's to do the location of my odbc.ini and odbcinst.ini files or something like that?
Just for reference:
/etc/odbc.ini:
[SERVER]
Driver = FreeTDS
Trace = No
Server = SERVER
Port = 1433
Database = DATABASE
UsageCount = 1
TDS_Version = 7.0
/etc/odbcinst.ini:
[FreeTDS]
Description = FreeTDS
Driver = /usr/lib/libtdsodbc.so
Setup = /usr/lib/libtdsS.so
FileUsage = 1
CPTimeout = 5
CPReuse = 20
Threading = 1
Thanks in advance for any help!
Ran into this problem today, it ended up being that I needed to specify a port number as part of the connection string. FYI.
It looks like I have just found a solution to this although I don't fully understand why. If the connection string used is:
"DRIVER={FreeTDS};SERVER=SERVER;UID=user;PWD=pass;DATABASE=DATABASE"
Then for some reason it doesn't work at all, I've tried using setting SERVER as both the IP and the actual name of the machine...no luck. However if I change the connection string to use SERVERNAME or DSN (can only have one of SERVER, SERVERNAME or DNS in the string) and I supply the machine name then it works fine, I can't get it to work with IP no matter what I try though. So, in summary the connection string that is working for me is:
"DRIVER={FreeTDS};SERVERNAME=SERVERNAME;UID=user;PWD=pass;DATABASE=DATABASE"
The key to this problem seems to lie in SQLDriverConnect.
I have the following code snippet:
SqlConnection sr = new SqlConnection(this.strConnection);
sr.Open();
Where connection string is:
Data Source = localhost;Initial Catalog=UIB_IS;Persist Security info=True;User ID=USR;Password=PSW;
(I have removed the user name and password from above for purpose of this question - I have double checked the password has not expired and is still the same.)
Every time I try to open the connection I get a failed exception.
I have also tried using the Microsoft.SqlServer.Management.Smo.Server() object with a string connection as well as a ServerConnection object. With the server connection object using a string and SQLConnection object.
None seem to be working.
Within the connection string I have tried the syntax ServerName\SQLSERVERNAME, 127.0.0.1 as well as localhost as you can see above.
Previously this code has been working over the last 6 months using the 'ServerName\SQSERVERNAME' syntax in the connection string on a Microsoft.SqlServer.Management.Smo.Server() object.
This last week.....no longer works.
No System updates have been applied. The DB and SQL User exist with the appropriate permissions set as were before. SQL Server still has allow remote connections set to allow.
The server firewall is also off (Development machine)
I cannot understand why it would suddenly stop working?
Anyone have any ideas?
Thanks in advance.
Be sure that your Sql Server allow remote connections. You can check its status under Sql Server Surface Area Configuration --> Surface Area Configuration for Services and Connection.
I am having a problem with a unit test I have created. First time doing this so I am not sure why I am getting this error
<DeploymentItem("ETDS.exe")> <DataSource("System.Data.SqlClient", "Data Source=Foo;Initial Catalog=FooDB;Integrated Security=True", "User_Names", DataAccessMethod.Sequential)> <TestMethod()> _
Public Sub ValidateUserNameTest()
Dim target As Login_Accessor = New Login_Accessor ' TODO: Initialize to an appropriate value
Dim expected As Boolean = True ' TODO: Initialize to an appropriate value
Dim actual As Boolean
actual = target.ValidateUserName
Assert.AreEqual(expected, actual)
End Sub
The error I am getting is
Test method ETDS_Unit_Tests.LoginTest.ValidateUserNameTest threw exception: System.Data.SqlClient.SqlException: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server).
This is the same connection that my software is using, and the software runs fine, only the unit test is failing. What I am doing wrong?
Edit
It Seems to fail one time for each datarow in the table.
Also, I am using a Linq Query in the method that I being tested. I believe that this may be what is causing my error.
Because you are using integrated security, the problem is most likely: "Who is running the test and what rights do they have to the network and/or the SQL Server?". If it's a local machine account, it probably won't even be allowed out over the network.
I noticed that your connection string does not have Server=
If you are connecting locally, it should have Server=(local)
Do you have the Foo alias setup in your local SQL Native Client config? Without that the "Data Source = Foo;" reference in your connection string won't work.
I've no idea if this is the same as the OP encountered, but the solution I found to a very similar problem was adding Provider=SQLOLEDB; to the connection string.