While trying to connect to SQLServer from C# the error # reported is 4060 and I get...
System.Data.SqlClient.SqlException HResult=0x80131904
Message=Cannot open database "MyDatabase" requested by the login. The login failed. Login failed for user 'DBClient'.
Source=.Net SqlClient Data Provider StackTrace:
When using the credentials from SSMS, all is good.
sqlConnect = new SqlConnection();
sqlConnect.ConnectionString = "Data Source = SlaDAS; Initial Catalog = MyDatabase; Uid = DBClient; Pwd = 123456PW; Connection Timeout = 30; Max Pool Size = 500";
sqlConnect.Open();
I have also tried a lot of different versions of the string and everything returns this error.
Thanks for all help, Stanley
We can get Visual Studio to help you generate a working connection string:
SELECT * FROM Person WHERE id = @id
- it doesn't matter what table, especially if you aren't going to use this strongly typed dataset as your data access layer.. Just make it any valid query as a testNow your settings file of your app contains a working connection string
You could use it from there, copy it etc if you're using EF, dapper or some other ORM, and throw the DataSet away but if you're planning on using data adapters and datatables like this:
using(var da as new DataAdapter("SELECT * FROM Person WHERE ID = @x", "Data Source=...."){
da.SelectCommand.Parameters.AddWithValue("@x", 1234);
var dt = new DataTable();
da.Fill(dt);
int age = Convert.ToInt32(dt.Rows[0]["Age"]);
...
}
Honestly it's easier and better to just do a tableadapter like:
var ta = new PersonTableAdapter(); //it's like a data adapter
var dt = new PersonDataTable(); //it's a datatable with extra properties so no casting
ta.FillById(dt, 1234); //load record with id 1234
int age = dt[0].Age; //it's an int already, no convert etc like above
You can add more queries to the tableadapter by right clicking it and choosing Add Query, e.g. so you can add SELECT * FROM Person WHERE FirstName LIKE @firstname
and call it FillByFirstNameLike then:
ta.FillByFirstNameLike(dt, "Jo%"); //find all person names starting with Jo
Or to return a datatable:
var dt = ta.GetDataByFirstNameLike("Jo%"); //get a new PersonDataTable
Use Visual Studio to help you create a working connection string using the wizards in a DataSet. As part of the process you'll have to get a working connection and you'll be able to easily prove it working and test downloading data/connection etc without tedious trial and error doing it in code. When you're done the correct connection string is in your settings/config and can just be used from there directly. You can discard the dataset, but if you're planning on using dataadapters and datatables to retrieve your data, it'll make life a lot easier to use the tableadapters and strongly typed datatables in the dataset instead
User contributions licensed under CC BY-SA 3.0