Having trouble connecting to SQL Server database from VBA using ADO connection - sql-server

I want to connect to a SQL Server database without using DSN. I'm receiving an error when trying to connect to said database. The error is
Run-time error '-2147467259 (80004005)': [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
My connection string looks like this:
"ODBC;DRIVER=SQL Server;SERVER=lokdb; UID=secret;PWD=secret;APP=Microsoft Open Database Connectivity;WSID=" & Environ$("COMPUTERNAME") & ";Network=DBMSSOCN;Trusted_Connection=Yes;DATABASE=EDMS-Lok"`
I am able to connect to the default database on the server with the credentials specified if I remove the DATABASE=EDMS-Lok parameter from the connection string, however I don't then seem to be able to "find" the EDMS-Lok database. E.g. if I try using
SELECT * FROM EDMS-Lok.dbo.eng_dwg
I get an error message
Run-Time error '-2147217900 (80040e14)': [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near '-'
(eng_dwg is a valid table)
When I connect without specifying a database, the .DefaultDatabase property of the ADO connection object returns "020" which I don't even see as an available database on that server??
When connected, if I use SELECT name FROM sys.databases I'm able to get a list of the databases available. They are:
010
100
500
EDMS-Lok
Master
msdb
MSLLockDB
pubs
tempdb
I got it working using DSN, but I don't want to use DSN.
Not sure what is wrong here??

I would say the problem is that you mix up the authentication models. You provide user + password but also you have configured trusted connection = yes. I'm not sure how ADO works in that case but I would assume that it doesn't use the configured user and connects with the windows account. Delete the trusted connection parameter in the connection string and try again.

OK, credit for this answer should go to Dee and Sam who commented on the original question, however I can't mark a comment as the answer, so here it is:
Needed to wrap the database name in square brackets [ ] ... like this DATABASE=[EDMS-Lok] - (credit to DEE)
I first tried wrapping the database name in the connection string i.e. DATABASE=[EDMS-Lok] and this did not work (same error). However, if I connect without specifying the database, I'm able to access the table using SELECT * FROM [EDMS-Lok].dbo.eng_dwg
It didn't work in the connection string because the string is not T-SQL code. To get it to work, you may need to figure out how to escape the dash character. – (credit to SAM)
I've tried single and double quotes, backslash, square brackets, parentheses and curly brackets and nothing seems to work to escape the hyphen in the database name within the connection string. But, since I can now access the database and the tables I need, which was the original question, I wanted to mark it as answered.

Related

How do I connect to an SQL server database in R

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.

Query with SQL Server 2008 R2 with FireDAC

I'm new to Firedac but not with Delphi
I can make a connection with SQL Server, and when I connect, there is no problem. I get connection OK. It works with code, with the wizard and with the FireDAC explorer.
The name of the database is :
C:\PROGRAM FILES (X86)\MICROSOFT SQL SERVER\MSSQL.1\MSSQL\DATA\3410b539-431f-4dff-ad0d-a574d1b13498.MDF
I'm stuck with a simple query.
SELECT *
FROM Account;
This query works from within the FireDac explorer but not from my program, I'm getting the following error:
[FireDAC][Phys][ODBC][Microsoft][SQL Server Native Client 11.0][SQL Server]Could not find server 'C:\PROGRAM FILES (X86)\MICROSOFT SQL SERVER\MSSQL' in sys.servers. Verify that the correct server name was specified. If necessary, execute the stored procedure sp_addlinkedserver to add the server to sys.servers.'
I'm also also getting the same error, when I try to do it from the UI within Delphi.
To try the query, I dropped onto the form a TFDQuery, the connection property was set automatically to the unique connection on the form. Then I set the query with the query editor, I get the error when I click on execute.
With code it like this :
FDConnection1.Connected := true;
FDQuery1.Close;
FDQuery1.SQL.Text := 'select * from Account;';
FDQuery1.Active := True;
When I debug the program, I get the error when setting the query active.
I see that the name of the DB is not complete in the error message. But it's complete in the component settings
Please advise,
I tried some extra test :
If I run the query from the UI editor (double-clicking on the FDConnection, Tab SQL Script), type the query, it works :-).
But when I try to do it on the FDQuery component, with the connection assigned to previous FDConnection, I get the same error. It' like some parameters are missing.
You are using the location of the SQL data file, instead of the name of the SQL Database.
If you do not know the name you can use the wizard to try and find it.
(Sorry could not add comments yet. This is also mentioned by Jens in the comments)
Update: if that is really the name, try enclosing it in [ ].
I got this response from an Embarcadero engineer:
The problem is not in FireDAC, but in SQL Server ODBC driver
SQLPrimaryKeys function. It fails to work with a catalog name
containing a dot. FireDAC uses this function to get primary key fields
for a result set, when fiMeta is included into FetchOptions.Items. So,
as a workaround / solution, please exclude fiMeta from
FetchOptions.Items.

How to connect to simple database table?

I don't know much about databases - Sorry if the question seems silly.
I have sql server 2012 on my machine and i create simple database table.
I want to connect to this database table thru C# code.
So, I need to know my ConnectionString.
I don't understand the parameters of the ConnectionString.
I try to google it - but still didn't find any good explanation.
Anyone can please explain the connectionString fields ?
How to define the connectionString that i will be able to connect the local database ?
thanks
Your connection string should be as simple as like below
Data Source=.;Initial Catalog=DB_NAME;Integrated Security=True"
Where
Data Source=. means local database
Initial Catalog=DB_NAME means the database it will connect to
Integrated Security=True means it will use windows authentication (no user name and password needed; it will use logged in credential)
Take a look Here
(OR)
Search in Google with key term sqlconncectionstring which will fetch you many help.
EDIT:
You are getting exception cause Initial Catalog=DB_Name\Table_001. It should be Initial Catalog=DB_Name (only database name). Provide the table name in sql query to execute. Check some online tutorial to get more idea on the same.
You use . in data source only when you are connecting to local machine database and to the default SQL Server instance. Else if you are using different server and named SQL Server instance then your connection string should look like
using(SqlConnection sqlConnection = new SqlConnection())
{
sqlConnection.ConnectionString =
#"Data Source=Actual_server_name\actual_sqlserver_instance_name;
Initial Catalog=actual_database_name_Name;
Integrated Security=True;";
sqlConnection.Open();
}
In case you are using local machine but named SQL Server instance then use
Data Source=.\actual_sqlserver_instance_name;
Initial Catalog=Actual_Database_NAME;Integrated Security=True"
using System.Data.SqlClient;
Then create a SqlConnection and specifying the connection string.
SqlConnection myConnection = new SqlConnection("user id=username;" +
"password=password;server=serverurl;" +
"Trusted_Connection=yes;" +
"database=database; " +
"connection timeout=30");
Note: line break in connection string is for formatting purposes only
SqlConnection.ConnectionString
The connection string is simply a compilation of options and values to specify how and what to connect to. Upon investigating the Visual Studio .NET help files I discovered that several fields had multiple names that worked the same, like Password and Pwd work interchangeably.
User ID
The User ID is used when you are using SQL Authentication. In my experience this is ignored when using a Trusted_Connection, or Windows Authentication. If the username is associated with a password Password or Pwd will be used.
"user id=userid;"
Password or Pwd
The password field is to be used with the User ID, it just wouldn't make sense to log in without a username, just a password. Both Password and Pwd are completely interchangeable.
"Password=validpassword;"-or-
"Pwd=validpassword;"
Data Source or Server or Address or Addr or Network Address
Upon looking in the MSDN documentation I found that there are several ways to specify the network address. The documentation mentions no differences between them and they appear to be interchangeable. The address is an valid network address, for brevity I am only using the localhost address in the examples.
"Data Source=localhost;"
-or-
"Server=localhost;"
-or-
"Address=localhost;"-or-"Addr=localhost;"
-or-"Network Address=localhost;"
Integrated Sercurity or Trusted_Connection
Integrated Security and Trusted_Connection are used to specify wheter the connnection is secure, such as Windows Authentication or SSPI. The recognized values are true, false, and sspi. According to the MSDN documentation sspi is equivalent to true. Note: I do not know how SSPI works, or affects the connection.
Connect Timeout or Connection Timeout
These specify the time, in seconds, to wait for the server to respond before generating an error. The default value is 15 (seconds).
"Connect Timeout=10;"-or-
"Connection Timeout=10;"
Initial Catalog or Database
Initial Catalog and Database are simply two ways of selecting the database associated with the connection.
"Inital Catalog=main;"
-or-
"Database=main;"

Connecting to Sql Server Database with hyphenated name

I don't seem to be able to find a way to escape this hyphenated database name so that I can open a connection to it. The database name is EDMS-Lok and my code looks like this (ADOcon is an ADO connection object):
strConBase="DRIVER=SQL Server;SERVER=LOKDB;UID=secret;PWD=secret;APP=LokENG_TESTS;WSID=LOKSPEC1;DATABASE=[EDMS-Lok];Network=DBMSSOCN;Trusted_Connection=NO;
ADOcon.ConnectionString = strConBase
ADOcon.Open"
I've tried the database name without enclosing brackets. I've tried enclosing it in square brackets, curly brackets, parentheses, back-ticks, single quotes, double quotes, etc. I've tried backslash and exclamation points. I can't find a way to escape the database name so that I can connect to it.
The error message I get is:
Run-time error '-2147467259 (80004005)':
[Microsoft][ODBS SQL Server Driver][SQL Server]Cannot open database "[EDMS-Lok]" requested by the login. The login failed.
The database name and credentials are correct. I can access it if I omit the database name argument from the connection string, and then use the fully qualified name in my SQL statements (i.e. SELECT * FROM [EDMS-Lok].dbo.tablename)
However, I really don't want to do this, as I'm trying to use modular code that does the same actions on multiple databases. What I want is to open the connection to one database, run some SQL procedures, close the connection, then open a connection to another database and run the same SQL procedures. Lather, rinse, repeat.
Also, before someone asks, I do not have the option of changing the database name.
As a test, I used the exact same connection string to connect to another database on the server that did not have a hyphenated name and it worked without error, so I'm pretty sure it's the stupid hyphenated name that is the problem.
I could not get this to work the way I wanted to through an ODBC connection using the MSDASQL provider.
I ran some tests and I seem to be able to connect through OLE DB using the SQLOLEDB provider. So, I think I will just go back and modify the existing code to use an OLE DB connection.
Using OLE DB, I've found I can leave the database name un-escaped, i.e. INITIAL CATALOG=EDMS-Lok; or I can escape using double quotes, i.e. INITIAL CATALOG="EDMS-Lok";. Square brackets however threw an error when I tried them, so for now I will stick to double quotes or un-escaped database names.
Thanks!

finding the correct connection string for a local SQL instance

I'm trying to build a connection string for a test environment that will connect to the local SQL Server instance on different machines. The purpose of this is so that a developer can checkout the code from TFS, build it, and run the testcases, connecting to his local DB. The problem is that different developer's machines may have different SQL Server setups. In particular, some may be running the full server, others may be running SQL Server Express.
I'm trying to right a utility routine that will take template connection string (e.g., Data Source=(local); Initial Catalog= myDB; Integrated Security=SSPI;) and modify the Data Source to work with the local server.
I've tried using SmoApplication.EnumAvailableServers() (returns an empty table, regardless of whether I user true or false parameters), and SqlDataSourceEnumerator.GetDataSources() (returns 2888 servers from the network, but none on the local machine), SQLCMD -L (returns nothing).
Any suggestions?
In the alternative, is there an easy way to tell whether a particular connection string will connect to a server (without waiting for it to timeout if it doesn't). If I could find the answer to that, I could try the likely suspects until I got one to work.
you might try to get the connection string as following:
Create a new blank file and name it test.udl.
Double click on it, and a "Data Link Properties" dialog should appear.
On "Providers" tab, select "Microsoft OLE DB Provider for SQL Server" or "SQL Native Client"
On "Connections" tab, try various settings and use the "Test Connection" button to test them. Click "Ok" when it works.
Open the test.udl file in Notepad and copy the line that starts with "Provider=" into your Web.config "ConnectionString" value, BUT delete the little part that says "Provider=SQLNCLI.1;"
If you want each developer to work with their own local SQL server, then the ADO connection string should have the Data Source set to localhost
... ; Data Source=localhost; ...
Additionally, to get a list of current servers, go to the command line and run
osql -L
You can look in the registry to find all local SQL Server instances. This key contains the list: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL.
Each named instance will have a value in this key. For named instances the name of the value is the same as the name of the instance. For the default instance the value will be named MSSQLSERVER.
This will do the trick:
Data Source=.\SQLEXPRESS

Resources