Fuppiz
Fuppiz

Reputation: 19

C# connecting to local SQL Server database with server's username and password

I am trying to build a custom connection string that would log in the user to a specific SQL Server user. I have tried many variations of the connection string but nothing works. here is the function.

Server license - developer

Crashes at the db.open(); statement.

Made a try catch around it and got this error 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

Can someone tell me what am I doing wrong?

    public string LoginAndGetRole(string username, string password)
    {
        using (SqlConnection db = new SqlConnection(@"Server=(local)\NLHospital;Integrated Security=false;user id=" + username + ";password=" + password))
        {
            using (SqlCommand getRole = new SqlCommand("findUserRole", db))
            {

                db.Open(); //crashes at this line
                getRole.CommandType = CommandType.StoredProcedure;
                getRole.Parameters.Add(new SqlParameter("@Username", username));
                SqlDataReader reader = getRole.ExecuteReader();

            }
            db.Close();
            return "";
        }
    }

EDIT : 1) My SQL server was configured ONLY for Windows Authentication.

Upvotes: 1

Views: 10832

Answers (4)

biz.tim
biz.tim

Reputation: 60

First, please check the NLHospital is your database instance name? or your database name?

Here is an example to you.

Data Source=ServerName\InstanceName;Initial Catalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True

Upvotes: 0

Janaka Neranjan
Janaka Neranjan

Reputation: 26

It seems like your Connection string format is wrong. Pls try below format with your parameters.Initial Catalog is your data base name.

= "Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=;

Upvotes: 0

Can you try this?

SqlConnection db = new SqlConnection(@"Data Source=(local); Initial Catalog=NLHospital; Integrated Security=false;user id=" + username + ";password=" + password)

or

SqlConnection db = new SqlConnection(@"Data Source=localhost; Initial Catalog=NLHospital; Integrated Security=false;user id=" + username + ";password=" + password)

Upvotes: 2

Chirag Rupani
Chirag Rupani

Reputation: 1715

I think your connection string is wrong. You should specify your database name in "Initial Catalog" or in "Database".

Please check sample connection strings at https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx

Upvotes: 0

Related Questions