简体   繁体   中英

I can't connect to my SQL Server 2014 database from Visual Studio 2012

When I try to open my SQL Server 2014 database, I get an error saying that

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

I can open my SQL Server and make databases and tables but when I try to connect them from Visual Studio I get this error.

Please help me out, I want to practice so I don't want this to stop me for a long time.

I write this code in Visual Studio:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Please Enter the Employee Id of whose Details has to be Updated");

        int Id = int.Parse(Console.ReadLine());

        SqlConnection conn = new SqlConnection("server=.;database=EmployeeDB;integrated security=true");

        string Query = "select * from EmployeeInfo where Id=" + Id;

        SqlCommand cmd = new SqlCommand(Query, conn);

        conn.Open();

        SqlDataReader dr = cmd.ExecuteReader();

        bool isRecordExists = dr.Read();

        if (isRecordExists)
        {
            Console.WriteLine("Employee Details are : \n");

            Console.WriteLine("Id is : {0}, Name is : {1}, Location is : {2} and Salary is : {3}",
                dr[0], dr[1], dr[2], dr[3]);
        }
        else
        {
            Console.WriteLine("No Employee Exists with the Above Entered Id");
        }

        conn.Close();
        if (isRecordExists)
        {
            Console.WriteLine("Please Enter the Updated Name");

            string Name = Console.ReadLine();

            Console.WriteLine("Please Enter Updated Location");

            string location = Console.ReadLine();

            Console.WriteLine("Please Enter Updated Salary");
            int salary = int.Parse(Console.ReadLine());

            cmd.CommandText = "UpdateEmployee";
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new SqlParameter("@Id", Id));
            cmd.Parameters.Add(new SqlParameter("@Name", Name));
            cmd.Parameters.Add(new SqlParameter("@Location", location));
            cmd.Parameters.Add(new SqlParameter("@Salary", salary));

            conn.Open();

            int noOfRowsAffected = cmd.ExecuteNonQuery();

            conn.Close();

            if (noOfRowsAffected > 0)
            {
                Console.WriteLine("Data Updated Successfully");
            }
            else
            {
                Console.WriteLine("Updation failed");
            }
        }
    }
}

Thanks in advance

See https://www.connectionstrings.com/sqlconnection/ . If you don't have Integrated Security or Trusted Connection on, you should be passing the User Id and Password attributes.

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