[c#] Connecting to SQL Server using windows authentication

When I was trying to connect to SQL Server using the following code:

SqlConnection con = new SqlConnection("Server=localhost,Authentication=Windows Authentication, Database=employeedetails");
con.Open();
SqlCommand cmd;
string s = "delete employee where empid=103";

I get the following error:

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: 25 - Connection string is not valid)

This question is related to c# asp.net sql sql-server

The answer is


You have to add a connectionString within your Web.config file as

<connectionStrings>
    <add name="ASPNETConnectionString" connectionString="Data Source=SONU\SA;Initial Catalog=ASPNET;Integrated Security=True"
        providerName="System.Data.SqlClient" />
</connectionStrings>

Then Write your SQL connection string as below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


public partial class WebPages_database : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ASPNETConnectionString"].ToString());
    SqlDataAdapter da;
    DataSet ds;

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void btnAdmnNumber_Click(object sender, EventArgs e)
    {
        string qry = "select * from Table";
        da = new SqlDataAdapter(qry, con);
        ds = new DataSet();
        da.Fill(ds);

        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
}

For more Information please follow this link How To:Connect to SQl with windows Authentication

SQL Server with windows authentication


Use this code:

        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = @"Data Source=HOSTNAME\SQLEXPRESS; Initial Catalog=DataBase; Integrated Security=True";
        conn.Open();
        MessageBox.Show("Connection Open  !");
        conn.Close();

use this code

Data Source=.;Initial Catalog=master;Integrated Security=True

I was facing the same issue and the reason was single backslah. I used double backslash in my "Data source" and it worked

connetionString = "Data Source=localhost\\SQLEXPRESS;Database=databasename;Integrated Security=SSPI";

Your connection string is wrong

<connectionStrings>
   <add name="ConnStringDb1" connectionString="Data Source=localhost\SQLSERVER;Initial Catalog=YourDataBaseName;Integrated Security=True;" providerName="System.Data.SqlClient" />
</connectionStrings>

Check out www.connectionstrings.com for a ton of samples of proper connection strings.

In your case, use this:

Server=localhost;Database=employeedetails;Integrated Security=SSPI

Update: obviously, the service account used to run ASP.NET web apps doesn't have access to SQL Server, and judging from that error message, you're probably using "anonymous authentication" on your web site.

So you either need to add this account IIS APPPOOL\ASP.NET V4.0 as a SQL Server login and give that login access to your database, or you need to switch to using "Windows authentication" on your ASP.NET web site so that the calling Windows account will be passed through to SQL Server and used as a login on SQL Server.


A connection string for SQL Server should look more like: "Server= localhost; Database= employeedetails; Integrated Security=True;"

If you have a named instance of SQL Server, you'll need to add that as well, e.g., "Server=localhost\sqlexpress"


This worked for me:

in web.config file;

<add name="connectionstring name " connectionstring="server=SQLserver name; database= databasename; integrated security = true"/>

Just replace the first line with the below;

SqlConnection con = new SqlConnection("Server=localhost;Database=employeedetails;Trusted_Connection=True");

Regards.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd