C
C#2mo ago
Adam

Trouble Connecting to Database

I'm using Dapper and SqlClient but I keep getting this error: Unhandled exception. Microsoft.Data.SqlClient.SqlException (0x80131904): 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: 35 - An internal exception was caught) here is the code:
using System.Data;
using Dapper;
using Microsoft.Data.SqlClient;

namespace MacBlazor2
{
public class DbHelper
{
private IDbConnection connection;

public DbHelper() {
connection = new SqlConnection("User ID=postgres;Password=password;Server=localhost:5432;Database=dvdrental;Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;");
Console.WriteLine(connection.Database);
Console.WriteLine(connection.ConnectionString);
foreach(Person p in connection.Query<Person>("SELECT actor_id, first_name, last_name FROM actor")) Console.WriteLine(p.first_name + " " + p.last_name);
}

}
}
using System.Data;
using Dapper;
using Microsoft.Data.SqlClient;

namespace MacBlazor2
{
public class DbHelper
{
private IDbConnection connection;

public DbHelper() {
connection = new SqlConnection("User ID=postgres;Password=password;Server=localhost:5432;Database=dvdrental;Pooling=true;Min Pool Size=0;Max Pool Size=100;Connection Lifetime=0;");
Console.WriteLine(connection.Database);
Console.WriteLine(connection.ConnectionString);
foreach(Person p in connection.Query<Person>("SELECT actor_id, first_name, last_name FROM actor")) Console.WriteLine(p.first_name + " " + p.last_name);
}

}
}
11 Replies
Adam
Adam2mo ago
the port is running and I can connect through the terminal to localhost:5432 using that login
Angius
Angius2mo ago
See how the error mentions "SQL Server" everywhere? Your database seems to be PostgreSQL
Adam
Adam2mo ago
but how does it get the port then
Angius
Angius2mo ago
?
Adam
Adam2mo ago
like how does it connect if it doesn't know the address of the server
Angius
Angius2mo ago
Well that's the problem It does not connect
Jimmacle
Jimmacle2mo ago
you need to use Npgsql, not Microsoft.Data.SqlClient
Angius
Angius2mo ago
You need the Npgsql nuget and use NpgsqlConnection instead of SqlConnection
Adam
Adam2mo ago
ah
Jimmacle
Jimmacle2mo ago
the ADO.NET providers are database specific
Adam
Adam2mo ago
I see my bad I'll try that out then