ODBC connection to SQL Server 2012 LocalDB instance - c#

We have a "legacy" application, which uses ODBC connections to an underlying database, which can be Access, Oracle or SQL Server. For unit (or, perhaps more properly, "integration") test purposes, I'd like to hook up a SQL Server 2012 LocalDB instance. However, I cannot figure out a correct ODBC connection string to use.
I have tried:
[TestMethod]
public void OdbcConnectionToLocalDb()
{
string connectionString = "DRIVER=SQL Server Native Client 11.0;Trusted_Connection=Yes;SERVER=(localdb)\v11.0;Description=LocalDB;";
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
using (var command = new OdbcCommand("select * from Person", connection))
{
connection.Open();
// ...
}
}
}
However, when the connection is opened, the following exception is thrown:
System.Data.Odbc.OdbcException: ERROR [08001] [Microsoft][SQL Server Native Client 11.0]Named Pipes Provider: Could not open a connection to SQL Server [67].
ERROR [HYT00] [Microsoft][SQL Server Native Client 11.0]Login timeout expired
ERROR [08001] [Microsoft][SQL Server Native Client 11.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online.
Is it possible to connect to a SQL Server 2012 LocalDB via an ODBC connection/driver? Is it possible to connect to a specific file?
[EDIT]
Garrett points out it is possible, great. I must have the connection string wrong, so my question really should be: what should the connection string be?

You need to specify your connection string like this:
Provider=SQLNCLI11.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TestDB;Data Source=(localdb)\v11.0
The main thing I think is that you reference it as a data source rather than server.

Yes, it's possible. Make sure you install the latest driver: SQL Server Native Client "Denali" (for ODBC and OLE DB).
Look here for more info:
http://blogs.msdn.com/b/sqlexpress/archive/2011/07/12/introducing-localdb-a-better-sql-express.aspx

Related

How to connect to a SQL Server instance with C# using Visual Studio

I am unable to connect to SQL Servers that have the '\' char which is used when connecting to a server instance. Any other type of server works without any issues. Any support or resource on this issue would be extremely helpful as I have exhausted my possible solutions.
Thanks!
Chris
I have tried:
- adding/removing the '#'
- using a double '\'
- hard coding the server name and connecting
var masterConnString = $#"Server={Server}; Database={ProjectCode}; Trusted_Connection=True;";
using (var connection = new SqlConnection(masterConnString))
{
connection.Open();
//do something
connection.Close();
}
The following error occurs:
System.Data.SqlClient.SqlException HResult=0x80131904 Message=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)
Source=.Net SqlClient Data Provider
Update:
When attempting to update the SQL Server Configuration Manager the connection fails due to lack of permissions.
Remove the trusted param and add this param
"Integrated Security=SSPI"
This always works with me when the server don't have any authentication

Visual Studio connects to database, but application within using the same connection string cannot

Using SSMS and Visual Studio 2015's Server Explorer tab under Data Connections, I can execute queries on remote server KOSH without issue. Why is the MVC application running locally in Visual Studio/IIS Express unable to do the same?
Using VS2015's connection Properties, I get its connection string:
Data Source=123.456.78.9;Persist Security Info=True;User ID=Foo;Password=Bar
Using that connection string, the MVC application is greeted with:
"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)"
Inner exception message:
"The network path was not found"
I know the server/firewall/network settings are correct. That leaves the application.
using(var connection = Database.Connection(conInfo.ConnectionString, provider)) {
// rowCountSql: SELECT SUM(rows) TM_ROWCOUNT FROM sys.partitions
// WHERE object_id = object_id(#tableName) and index_id IN (0,1)
// Any other SQL yields same error
var countTask = connection.QueryAsync(rowCountSql, new { tableName = Editor.TableName });
}
Async is used because the Oracle version of the query can take several seconds to return.
The application should be correct because it connects to the same server from home (also the server's location) and to identical databases in remote data centers running 2008R2 to 2014 without a problem.
Database.Connection() is:
// This is unlikely to be the problem as it is very well tested
public static DbConnection Connection(string connectionString, string databaseProvider) {
DbProviderFactory databaseFactory = DbProviderFactories.GetFactory(databaseProvider);
DbConnection connection = databaseFactory.CreateConnection();
if(connection != null)
connection.ConnectionString = connectionString;
return connection;
}
I bet I am missing something simple, but I would be grateful for help on what that could be.
As I said in comments, maybe the piece of your code:
conInfo.ConnectionString
does not contains the correct connection string you want.
Check it out

SQL Server problems to connect

I am developing a program with C# and WPF. I want the data to be stored in an SQL Server database. I made a connection string with the instance name in my PC, and that worked. But when I want to connect through the Internet with an IP address, I get some errors:
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. (TCP Provider,
error 0 - No connection could be made because the target machine
actively refused it.)
I enabled TCP/IP, allowed remote connection in SQL Configuration Manager, opened a port of 1433 in my firewall, but still I am getting this error.
My connection string is this:
String connString = #"Network Library=dbmssocn;
Network Address=127.0.0.1,1433;
Integrated security=SSPI;
Initial Catalog=db";
SqlConnection conn = new SqlConnection(connString);
conn.Open( );
Where is my mistake?
There is very slight error in your connection string and honestly I can't blame you for that as it is very weird way in which SQL Sever is behaving. I'm not sure if this error lies in connection provider side or SQL Server instance side. Name of Network Library that your application is using to connect to the SQL Server using dbmssocn(Win32 Winsock TCP/IP) should always be mentioned in capital letters. Though I didn't see any relevant MSDN documentation from MS to support my statement but it actually worked when I did so. Here is the connection string that you should be using to fix the error.
String connString = #"Network Library=DBMSSOCN;
Network Address=127.0.0.1,1433;
Integrated security=SSPI;
Initial Catalog=db";
Seriously, I got freaked out in reproducing your issue as instead of copying the connection string from your question I copied it from some other blog :). But all is well that ends well. I've also assumed that a database named "db" actually exists on the default (NOT named instance) instance of the sql server you are connecting to when typing this answer. If changing the casing of network library name in connection string doesn't help then double check that database "db" must exist for a sql server default instance to which you are connecting to. In case you are using a named instance of sql server in your installation then that instance name should also come in the connection string.
Configure your SQL Server to allow TCP/IP connections. Go to SQL Server Configuration Manager -> network then protocols for your SQL Server named instance -> TCP/IP.
See this image!

Connection string to SQL by EntityFramework and MVC

I write web page in MVC, which use Entity Framework as ORM mapper. I put my connection string to web.config file. Here is it:
<add name="JP_CMS" connectionString="Data Source=.;Initial Catalog=JP_CMS;
User Id=CmsWebUser;Password=abcd1234abcd1234;"
providerName="System.Data.SqlClient"/>
I try to get data by this C# code
public DataBaseContext()
: base("JP_CMS")
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<DataBaseContext>());
}
//------------------------------
var db = new DataBaseContext();
var result = db.Articles.ToList(); //<- here is thrown exception
//------------------------------
My local SQL server is running, this table is exists, but I get excepion like in this:
I think it is the most important expection: "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)"
Could you help my by give some idea what I make wrong?
"The system cannot find the file specified" error. Check carefully your connection string.
hi Error indicates EF tried to connect to the server but failed.
Could you Checkk,
1) SQL Server should be up and running.
Go to All Programs >> Microsoft SQL Server 2008 >> Configuration Tools >> SQL Server Configuration Manager >> SQL Server Services, and check if SQL Server service status is “Running”.
In addition, ensure that your remote server is in the same network. Run “sqlcmd -L” in your command prompt to ascertain if your server is included in your network list.
2) Enable TCP/IP in SQL Server Configuration
For more info you can go here
Instead of DataSource =. try DataSource = .\sqlInstanceName. Also DataSource=(local) might work.

Can't connect to SQL Server 2005 Express from an ASP.NET C# page

I have an MS SQL Server 2005 Express running on a VPS.
I'm using pymssql in Python to connect to my server with the following code:
conn = pymssql.connect(host='host:port', user='me', password='pwd', database='db')
and it works perfectly.
When I try to connect to the server from an ASP.NET C# page with the following code:
SqlConnection myConnection = new SqlConnection("Data Source=host,port;Network Library=DBMSSOCN; Initial Catalog=db;User ID=me;Password=pwd;");
myConnection.Open();
When I run the ASP.NET page I get the following exception at myConnection.Open();:
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: TCP Provider, error: 0 - A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.)
I tried restarting the SQL Server but I had no luck.
Can anyone point me out to what I'm missing here?
Thanks!
Let's say your host is localhost. When you are using SQLEXPRESS you need to specify that in your Instance Name.
Loke this: Data Source=localhost\SQLEXPRESS if it is bound to localhost. Otherwise it might just work with: Data Source=.\SQLEXPRESS.
If you have management studio installed you can fire that up and check what connection string it is using!
Still doesn't work..
I'm able to connect to the remote server with SQL Management Studio.
I enter host,port\SQLEXPRESS (of course I my actual IP number as the host and my actual port) in the Server Name field, select SQL Security and enter my username and password and it works perfectly.
When I try to connect from the ASP.NET page, it just doesn't work - I get the error aforementioned. Can it have something to do with the company hosting my asp.net page? (GoDaddy)
here is the code again..(assuming my host is 11.22.33.44 and my db is named bla
string connectString = #"Data Source=11.22.33.44,1433\SQLEXPRESS;Network Library=DBMSSOCN;Initial Catalog=bla;User ID=username;Password=pwd;";
SqlConnection myConnection = new SqlConnection(connectString);
myConnection.Open();
Thanks again

Categories

Resources