F Scott Fitzgerald

Total Post:28

Posted by  F Scott Fitzgerald
 1515  View(s)
Rate this:
Hi Expert,

Hi I have been trying all day to connect to my local sql-server database using ODBC but I seem to be missing something because every time I am trying to conenct I get this error:

ERROR [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database "Library.mdf" requested by the login. The login failed.

my source code as following

 private string connectionString;

    public LibraryRepository()
        connectionString = @"Driver={SQL Server};Server=(local);Trusted_Connection=Yes;Database=Library.mdf;";

    public IEnumerable<Book> GetPersonDetails()
        using (var conn = new OdbcConnection(connectionString))
            using (var command = new OdbcCommand("SELECT * FROM Books" , conn))
                var reader = command.ExecuteReader();
                while (reader.Read())
                    yield return new Book()
                            Id = (int) reader["Id"],
                            Name = (string)reader["Name"],
                            Author = (string)reader["Author"],
                            Description = (string)reader["Description"],
                            Price = (string)reader["Price"],
                            CategoryId = (string)reader["CategoryId"]
I am not really sure that the conenction string is ok when I look at the properties of the database at connection string I see this line :

Data Source=(local);Initial Catalog=Library;Integrated Security=True

But if I add this line as the connection string I get this error:

ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified
In order to veify if the data source is ok I logged into SSMS with (local) server name and it works I can also see my database there.

I have also set NT AUTHORITY\NETWORK SERVICE as the db_owner after reading a blog about this issue but still I get the error Cannot open database "Library.mdf" request by the login.

I am not really sure what to do next to solve this problem.Can anyone provide some suggestions?

  1. Dev Patel


    Re: Odbc connection string results in login failed

    Hi Expert,

    The connection string is wrong. You should write the name of the database not the name of the file MDF that could contain many databases

    connectionString = @"Driver={SQL Server};Server=local);" + 

    When you open your database with SSMS you should expand the Database node and look at how your database is called, then replace the question marks with that name

  1. Ankit Singh


    Re: Odbc connection string results in login failed

    Try this:

    connectionString = @"Driver={SQL Server};Server=local);" + 

      Modified On Apr-05-2018 06:21:25 AM



Enter your email address here always to be updated. We promise not to spam!