1

I want to retrieve all the registered users from my application using web service in ASP.NET. However, I have problem with connection string.

public static String getRegisteredUsers(string usernameCode)
    {
        string username = "";

        SqlConnection con = new SqlConnection("MyDatabaseConnectionString1");
        SqlCommand cmd = new SqlCommand("Select Username from Users where usernameCode = '" + usernameCode.ToUpper() + "'", con);
        con.Open();

        SqlDataReader dr = cmd.ExecuteReader();

        while (dr.Read())
        {
            username = dr["username"].ToString();
        }

        dr.Close();
        con.Close();

        return username;
    }

This MyDatabaseConnectionString1 is the connection string that I use for the table that I want to retrieve the information from. It works for that table, but not when it comes to web service.

<add name="MyDatabaseConnectionString1" connectionString= "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Korisnik\Desktop\Fitness\App_Data\MyDatabase.mdf;Integrated Security=True"/>

Should I use the same connection string for web service or it's done somehow differently ?

This is the error: enter image description here

Seinfeld
  • 433
  • 7
  • 24
  • The connection string is missing the initial catalog? See the [MSDN page.](https://msdn.microsoft.com/en-us/library/d7469at0(v=vs.110).aspx) However, unless you have multiple databases on that server, [it shouldn't matter](http://stackoverflow.com/a/1949790/6530134)... [possibly](http://stackoverflow.com/questions/1949774/what-is-the-point-of-initial-catalog-in-a-sql-server-connection-string#comment1862783_1949790)? – Timothy G. May 10 '17 at 11:10
  • SqlConnection expects the connection string, not the name of the connection string. – Crowcoder May 10 '17 at 11:12

2 Answers2

2

You should not use MyDatabaseConnectionString1 (name of the connection string) directly as input for SqlConnection (which expects connection string as the input). Do this instead:

string connStr = ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString1"].ConnectionString;
SqlConnection con = new SqlConnection(connStr);
... //continue as what you have done

You declare your MyDatabaseConnectionString1 in the .config file. The SqlConnection does not read your .config file but take the connStr input. Thus you get the error. You should read your connection string in the .config file by using ConfigurationManager available in the System.Configuration namespace. Then you use the connStr resulting from reading the .config file

Ian
  • 30,182
  • 19
  • 69
  • 107
1

Ensure System.Configuration assembly is referenced. Use this syntax:

 SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MyDatabaseConnectionString1"].ConnectionString);
Alkis Giamalis
  • 300
  • 7
  • 14