简体   繁体   中英

While I connect to database using ADO.NET there is an error

While I establish a connection to SQL Server using ADO.NET, it showing errors.

Following is the code:

SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=abdul;Integrated Security=true");
SqlCommand cmd = new SqlCommand();

con.Open();

String str="select * from emp where empname='Abdul'";
cmd = new SqlCommand(str, con);

SqlDataReader dr = cmd.ExecuteReader();

if (dr == null || !dr.HasRows)
{
   MessageBox.Show("No Records found");
}
else
{
   while (dr.Read())
   {
      textBox1.Text = dr[0].ToString();
      textBox2.Text = dr[1].ToString();
   }
}

When I am running the project it showing the following error:

Cannot open database "abdul" requested by the login. The login failed.

What have to do?

The login is successful at the the SQL Server level. Then either

  • the database exists but the login you are using doesn't have access to the database
  • the database doesn't exist

In SSMS, go to adbul database. Expand the security node and add the relevant users (which map to the login) + security there. If you still can't, have you created the database single user?

It's hard to give more details at the moment.

You need to check that the user you are connecting with is a valid SQL Login, and that the password supplied is correct. You also need to ensure the login has an associated SQL User in the database they are trying to connect to.

SQL Logins are used to access the server itself, and they are mapped to database SQL users.

You said you created the database. How did you do this? Was it from sql management studio? If so, was this in the same Windows session as you are executing the program code above?

I ask because if you could create a database, I believe you should be able to connect to it.

I'd look at the difference between successfully connecting with Sql Management Studio and trying to get past the 3rd line of code in your question. (assuming that's where it fails, maybe even edit the question to take out the lines beyond).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM