Error trying to establish connection to SQL Server Express - c#

I created a web site in Visual Studio 2012 that interacts with a SQL Server Express database table where the database was created beforehand with SQL Server 2008. I added the connection with the database to the site, and all of this worked fine.
Now I am doing exactly the same with a new website but now get the error message.
System.Data.SqlClient.SqlException (0x80131904): Login failed for user ''
The error happens as I am trying to make the connection and with my previous project everything was fine and still is, exactly the same connection string was used in both cases. From where does this exception come from all of a sudden?
try
{
connectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=Employee,Integrated Security=True;";
using (conn = new SqlConnection(connectionString))
{
conn.Open();
.....
}
}
How can I resolve this?

you have invalid connection string, you have used , instead of ;
connectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True;";
// ^ here
List of Connection Strings for SQL Server 2008

Related

Connecting to a remote SQL Server (SQLExpress) gives "network-related" error, but works using Server Explorer in Visual Studio

I am using NET 6.0 and I cannot make it work.
I am trying to connect using:
var builder = new System.Data.SqlClient.SqlConnectionStringBuilder
{
DataSource = $"{ip}\\SQLEXPRESS, 1433",
InitialCatalog = "xxx",
UserID = "user",
Password = "pass"
};
SqlConnection thisConnection = new SqlConnection();
thisConnection.ConnectionString = builder.ConnectionString;
thisConnection.Open();
However, I keep getting this
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 - No connection could be made because the target machine actively refused it.)
Using exactly the same code on Netframework 4.8 works. Anybody care to explain why? Using the same machine as above, if I use the Server Explorer in Visual Studio then the connection is successful. Also works using Python. I tried ussing the connection string from the Server Explorer connection string and still doesn't work. The connection string from that works using the Server Explorer:
Data Source=xxx.xxx.xx.xx\sqlexpress;Initial Catalog=database;Persist Security Info=True;User ID=sysdba;Password=****
Here is the Server Explored connected:
And the properties:
And then:
SqlConnection conn = new SqlConnection();
conn.ConnectionString = #"Data Source = xxx.xxx.xx.xx\sqlexpress; Initial Catalog = database; Persist Security Info = True; User ID = sysdba; Password = ******";
conn.Open();
But still fails to connect.
I also set the port to 1433 like suggested in Cannot Connect to Server - A network-related or instance-specific error and restarted the service
Also
And still fails to connect using the SqlConnection() (still works using the Server Explorer).
What am I doing wrong?
The SQL Server uses SQL Server Authentication, no Windows Credentials. I connect using IP\sqlexpress.
It doesn't seem to be a network related issue, like I saw in other answered questions, since it is working using the Server Explorer in Visual Studio and also in Python.
I was facing the same issue (Net 5.0). You can use the Connnected Services, which is a collection of tools in Visual Studio that will help you connect to the database. I believe this may be a different approach, but it should work since visual studio will be creating the connection string (same was as per Server Explorer).
https://learn.microsoft.com/en-us/visualstudio/data-tools/add-new-connections?view=vs-2022
https://learn.microsoft.com/en-us/visualstudio/azure/overview-connected-services?view=vs-2022

Sql connection string via SqlClient

I have an issue trying to manually connect to a sql server on my network.
I have a web API with a conn string that works fine, I have a VS2015 winforms project i set up to test the conn using the VS tool to connect, this also works fine.
However when i try to connect via SQLconnection it fails and says the server cannot be found or isnt accessable.
So heres the test code...
string connectionString = #"Data Source=test1\test1;Initial Catalog=my_test;Integrated Security=True;";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
// Create the Command and Parameter objects.
SqlCommand command = new SqlCommand("", connection);
// Open the connection in a try/catch block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}\t{2}",
reader[0], reader[1], reader[2]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
Now i dont really care about results or anything i simply need to establish a connection. I cant figure out why it throws this error, when my Web API works and the VS tool for connection to DBs works fine too.
I have checked the server and enabled named pipes too just to make sure.
Any ideas?
EDIT:The error i catch...
{"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)"}
happens after about 15 seconds trying to open the connection.
The thing is this connectiin string i tried is the exact same string used via the SQL tool, I did this so i knew i had a valid string.
ODBC connection also falls over with the same message.
I checked from my machinbe is i can listen to port 1433 but it says the server isnt listening.
However looking at the server its set to dynamic ports with a range of any to 41934, so im at a loss as to why it says its not listening evenb though its to dynamic ports
EDIT2: Well, must be permissions or drivers... just tried the exact same code and worked instantly...
This is diving into the realm of the unknown i feel. might ask for deletion of the question if no solution is found
I think that i see the problem:
string connectionString = #"Data Source=test1\test1;Initial Catalog=my_test;Integrated Security=True;";
Integrated Security is used for local logins, You could make an account in the database and change the connection string to:
string connectionString = #"Data Source=test1\test1;Initial Catalog=my_test;User id=<Username>;Password=<Password>;";
I hope this helps!

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

C# Sql Server setting datasource = localhost

When I change my sql server Connection to:
SqlConnection dbConn = new SqlConnection("Data Source=localhost; Initial Catalog = Semester 2 Project SD; Integrated Security=SSPI");
It gives me an error saying that it cant find the server or can't connect to it.
Is my string/ sql connection completely wrong or is there anything i need to change in SQL server, or both?
When I use server = BACON1-PC\\SQLEXPRESS it works completely fine though.

windows Application Database Connection c#

Im facing problem with database connection on windows Application Database Connection c#... here is my connection ,,, PC2 is PCNAme
private static SqlConnection con = new SqlConnection(
"Data Source=PC2\\SQLEXPRESS; Initial Catalog=Database1;Integrated Security=True"
);
when I run the form I get this unhandled exception on con.Open();
sqlException was unhandeled:
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: SQL
Network Interfaces, error: 26 - Error Locating Server/Instance
Specified)
hope some one can help Im trying to solve it for many hours but not working.
Check this trouble shoot steps on MSDN:
The SQL Server client cannot connect to the server MSDN
And much better if you separate your connection string to your ado.net sql connection.
private const string _thisConnectionString = "Data Source=PC2\\SQLEXPRESS; Initial Catalog=Database1;Integrated Security=SSPI";
Use the "Using" Statement ensure that you always close your Connection.
Best Practices for Using ADO.NET MSDN
using (var conn = new SqlConnection(_thisConnectionString))
{
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = "Your SQL Query STuff";
conn.Open();
}
Regards
Try This:
private static SqlConnection con = new SqlConnection(
"Data Source=PC2\SQLEXPRESS; Initial Catalog=Database1;Integrated Security=True"
);
Go to SQL Server Configuration Management -> Click on SQL Server Services
Verify SQL Server and SQL Server browser both are running. you can see a Greed play button there. if it's not running right click on the service which shows Red, go to properties, Click Built in Account and Press Apply then OK, There try to start by right click.

Categories

Resources