Cause Of SQL Connection Error - c#

Within my ASP.NET C# WebForms app I am attempting to connect to my SQL Database.
Upon connection I get the error:
ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
I've attempted to google what this error means but the results do not clearly explain whats wrong. Can you tell me what exactly is wrong (its not finding the database file, it found the file but the database file is incorrect version, etc.)?
These are the steps I have performed:
Create a local database using VS2013. The file is located in 'MyProjectPath\App_Data\Pages.mdf'
The database is populated with a table and rows
I have connected to the server by 'Server Explorer->Connect To Server->Type in my computer username'. No errors appear
In the Server Explorer I have tested my connection to the database and it succeeded.
Connection is 'Microsoft SQL Server Database File (SqlClient)'
I have copied the 'ConnectionString' to web.config. One important thing is that the string contains quotation marks and I have to remove these.
Do I need to start an external application like SQL Server Management Studio or something?
Connection String:
Data Source=(LocalDB)\v11.0;AttachDbFilename="C:\VERY_LONG_PATH_THAT_HAS_SPACES\App_Data\Pages.mdf";Integrated Security=True
I remove the quotations:
<connectionStrings>
<add name="MySQLConnStr" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\VERY_LONG_PATH_THAT_HAS_SPACES\App_Data\Pages.mdf;Integrated Security=True"/>
</connectionStrings>
// My simple connection code where the runtime error occurs
try
{
using (OdbcConnection connection = new OdbcConnection(ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString))
{
// do stuff
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

Hi to make ODBC connection you need to have driver installed. You can make sql connection and this should work..
// Change your simple connection code to
try
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString);
connection.open();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}

Try one by one below three solutions, it will help you to solve your problem.
You need to configure DSN in Administration Tools => ODBC, When install driver choose for all users instead current user
Try to look on your server for the ODBC Data Source Administrator that can be found in Control Panel --> Administrative Tools --> Data Sources (ODBC). (On 64 bit Windows systems, you'll have to explicitly call c:\windows\syswow64\odbcad32.exe ) and add the driver to the System DSN tab.
If the ODBC driver was not 64 bit, Try to compile your application as an x86 process and it will work.

Related

Can not connect to Sql database in C# asp mvc application with Entity Framework BUT the same code works with Winform application

First of all, please excuse me if it sounds too rooky. I consider myself novice in MVC applications.
I have ran into a strange problem and there does not seem to be any way out of this, at least so far..I have looked everywhere and left no stone unturned to get it worked. Finally I turned to this forum.
This is my first post, so any mistakes please overlook and guide me.
The problem is multifaceted...
The High Level Details...
I have created a C# ASP MVC Web Application waiting to be uploaded on a Remote Server (Client Machine)
The application uses Entity Framework - Code First approach
Connects to the database with Windows Authentication system
Scene1: Where the application worked
I have tested the application on my machine and it worked flawlessly.
I have Express edition of Sql Server Management Studio installed on my system.
Scene2: Where the application failed. The Problem - Big Picture
It works great on my system but while testing it on the Remote Server it crashes
The application fails to connect to the Remote Server Sql Database. As soon as it tries to connect to the database, it crashes with an error message "Login failed for user '<UserName>."
I have checked everything in the connection string - like -
Data source name is correct
Initial Catlog also points at the correct database name
Integrated Security = true
There is no UserID or password mentioned
Connection string worked great on my system. But it does work on the Client Machine and shows the error above.
Connection string is:
connectionString="Data Source=RemoteComputerName;Initial Catalog=DatabaseName;Integrated Security=True; MultipleActiveResultSets=true"
I am not able to figure out exactly what is causing the error - Is it my code or Is it the Sql Server database settings - permissions.
Since the connection worked on my local machine, which means the code is correct
In order to check whether sql server permissions are working..I have created partial 'test connection application' in WINFORM and uploaded on the Server, this time the code works and read all the table data.
but when I try to connect in MVC project it shows the error..."Login failed for user...".
I'm totally confused what works in WINFORM fails in MVC.
Database permissions must be right because when tried to access it using WINFORM it worked.
please let me know if I have missed to provide any details in this post.
Any help is highly appreciated!!!
Thank You.
Please show your connection string. (you can block out any real passwords, actual server names, actual db names).
Since you mention "Integrated Security = true"..........then you have to be aware of which Identity is running the process (the website or the winforms.exe)
When running as winforms app, you are running as "you" (most likely). As in, the logged in user to the windows o/s.
When running under IIS, you are running under the Identity associated with the App Pool you are using..which most likely is NOT you, but rather a service account.
Your service-account does not have access to the sql-server.
You can read in depth here: https://support.microsoft.com/en-us/help/4466942/understanding-identities-in-iis#:~:text=ApplicationPoolIdentity%3A%20When%20a%20new%20application,also%20a%20least%2Dprivileged%20account.
You can show this......by catching an exception, and then something like this:
You can replace ArithmeticException with whatever, I'm just showing "adding info" to a caught exception and rethrowing.
try
{
// some sql server access code
}
catch(Exception ex)
{
throw new ArithmeticException("What is the real IIdentity: " + this.FindIIdentity(), ex);
}
private string FindIIdentity()
{
try
{
//'Dim user As WindowsPrincipal = CType(System.Threading.Thread.CurrentPrincipal, WindowsPrincipal)
//'Dim ident As IIdentity = user.Identity
string returnValue = string.Empty;
WindowsIdentity ident = WindowsIdentity.GetCurrent();
returnValue = ident.Name;
try
{
returnValue += " on " + System.Environment.MachineName;
} catch (Exception ex)
{}
return returnValue;
} catch (Exception ex)
{
return "Error Finding Identity";
}
}
IIS screenshots

SQLiteException: 'unable to open database file'

As shown in pictures, "ProjectDB.db" is a database I built through the SQLite Compact Toolbox. The database indeed exists in that folder path. The exception as in the title is thrown as I debug the app.
UWP App. Visual Studio 2017. Windows 10.
Snapshot of Errors while running application
enter image description here
enter image description here
Connection string for connecting SQL lite Database
SQLiteConnection db =
new SQLiteConnection(#"Data Source=C:\Users\georg\source\repos\DatabasePractice\ProjectDB.db;Version=3;";
db.Open();
Sqlite on Windows a directory/path should use a double backslash like this:
C:\\Users\\georg\\source
If this does not solve your problem, attempt these troubleshooting steps:
Is the Database stored on a remote server or 'read-only' directory?
Is the parent directory a 'read-only' directory?
Try executing your code with the Source="...Practice\ProjectDB;" not "\ProjectDB.db;"
Is something else attempting to read the database? Although this should throw a 'database locked' exception which makes this one unlikely.
I was facing same issue on the shared hosting server, My C# code was able to read data from SQLIte db file. But while add / update data it was throwing Error "unable to open database"
I tried many options suggested on stackoverflow But after referring https://stackoverflow.com/a/17780808/2021073 and
https://www.sqlite.org/pragma.html#pragma_journal_mode I tried adding journal mode=Off; to the Connection string
and it worked for me
sample code
SQLiteConnection connection = new SQLiteConnection("Data Source=G:\dbfolder\sqlite3.db;Version=3;Mode=ReadWrite;journal mode=Off;", true);

oracle connection string with SID in c#

Hi I have to connect to an Oracle Database( about which I know a little) using a windows application.
The windows application will not necessarily be in the same system.
I just needed the connection string.
So I Used Add connection functionality in Visual Studio 2014 to test the connection and get the string.
eedb is the SID which i read in stackoverflow question
Now using above, i was able to connect to the database using this functionality and even in my visual studio server explorer all the tables of the oracle database were showing but I needed to use the connection string in the windows application.
So I used following string:
DATA SOURCE=172.31.8.21:1521/eedb;USER ID=PDB_E_GND_R
I added password too to this string as
DATA SOURCE=172.31.8.21:1521/eedb;USER ID=PDB_E_GND_R;PASSWORD=123
when i run the application i get error.
System.Data.OracleClient.OracleException: ORA-01017: invalid username/password; logon denied.
So :
Why I am getting this error. Now some may mark this question as duplicate and even point out the answer can be found in issue stackoverflow question
Coz if this was the case I would have been unable to establish connection through add connection functionality of Visual Studio at all.
Please note: I added the reference: Oracle.DataAccess
And also for a programmer like me who has very little knowledge regarding the oracle.
How I can know which connection string I have to use for a particular oracle db.
Try the following connection string EZ connect does not seem to be so EZ
data source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = 172.31.8.21)(PORT = 1521)))(CONNECT_DATA =(SERVICE_NAME = eedb)));USER ID=PDB_E_GND_R;PASSWORD=123

First chance exception of 'System.Data.EntityException'. The underlying provider failed on Open

I've been given a site that was created by someone else and I'm now trying to test it. I can compile the system without any problems but when I try to log in to the website, I get the error:
"EntityException occured. A first chance exception of type 'System.Data.EntityException' occured in System.Data.Entity.dll. Additional info: The underlying provider failed on Open."
Furthermore, if I dig deeper, I see an InnerException of Cannot open database \"MyDB\" requested by the login. The login failed. Login failed for user 'name\\owner'.
I've read similar problems on the web and it seems like its a problem with database connections? I've tried multiple 'solutions' that include messing around with the connectionString but nothing works.
What I think the system wants to do is connect to a .mdf located in a separate project's App_Data. Anyway, here's the connectionString code that I received originally:
add name="NameServiceContext"
connectionString="Server=tcp:qiu5vg5yhv.database.windows.net,1433;Database=MyDB;User ID=MYID;Password=MYPASS;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;"
providerName="System.Data.SqlClient"
Quick question, what is the tcp:...... stuff? I'm assuming it was generated somehow, but how?
I've tried 'fixing' the problem and ended up with something like this:
add name="NameServiceContext"
connectionString="data source=./SQLEXPRESS;AttachDbFilename=C:\Users\owner\Documents\MyERP\App_Data\MyDB.mdf;Integrated Security=True;Connect Timeout=30;"
providerName="System.Data.SqlClient"
Both methods give the same errors and I'm out of ideas. How would I go about fixing this?
Also, when I connect to a db via tools>connect to database > MS SQL db file, I get an option between 2 data sources, ./SQLEXPRESS and (LocalDB)\v11.0. Do I have to include both of them? If so, how?
The original connection string refers to a Microsoft Azure instance. A typical connection string to Azure looks like:
Server=tcp:[serverName].database.windows.net;Database=myDataBase;User ID=[LoginForDb]#[serverName];Password=myPassword;Trusted_Connection=False;Encrypt=True;
Your server name is qiu5vg5yhv.database.windows.net. Most likely your credentials are incorrect.
It is as Andrew said, you don't seem to have access to the actual database. Simply download either "SQL Server Management Studio" or "SQL Server Management Studio Express" (depend on which version of database you are using) and try to connect.
If you connect successfully, check if you can query the database of your project.
If you connect unsuccessfully, contact your system admin to arrange access.
If you want to understand more about connectionstring or create one, use the following site for template: http://www.connectionstrings.com/sql-server/
You can get the necessary database details by viewing the Properties of your database via "SQL Server Management Studio" (right click and select Properties --> View Connection Properties)
I met the same question. The key step is here.
I used vs 2013 update 4.
When you configured your SQL in azure, it generated a connect string.

Desktop application - Unable to connect to any of the specified MySQL hosts

I'm developing desktop application with MS Visual Studio 2008 c# and i'm trying to connect to mysql database. I download connectors, added references and i have this code:
try
{
MySqlConnection conn = new MySqlConnection("server=127.0.0.1;User Id=user;Pwd=pass;database=db");
conn.Open();
}
catch (MySqlException exp)
{
Console.WriteLine(exp.Message);
}
On conn.Open(); i got MySqlException Unable to connect to any of the specified MySQL hosts. The worst part is that i can connect to database throw Server Explorer in MSVStudio.
I reviewed all similar questions, but I didn't get answer!
Pls help!
I realize this question is a couple of years old but I was having the same problem in VS2015 Community Edition when trying to open the Query Builder in the DataSet Designer. I searched all over the web trying to find a fix and none of them worked. Finally I found the answer by accident.
What is happening is VS doesn't realize that it has to open a connection first, the error message is very misleading. To remedy the problem all you need to do is in the Server Explorer under the Data Connections find the connection that you are working on and simply double click on it to open. That's it!
If you look at the Icon next to the Connection you will notice that it changes from to showing that the connection is open.

Categories