I am trying to create a database programmatically and create a table in it.
This is my code :
string connectionstr = string.Format(@"Data Source=.\sqlexpress;Initial Catalog={0};Integrated Security=True", "books");
SqlConnection myConn = new SqlConnection(connectionstr);
DirectoryInfo dir = new DirectoryInfo(@"D:\Data");
dir.Create();
string str3 = @"CREATE DATABASE [books] ON PRIMARY
( NAME = N'books', FILENAME = N'D:\DATA\books.mdf' , SIZE = 3072KB , FILEGROWTH = 1024KB )
LOG ON
( NAME = N'books_log', FILENAME = N'D:\DATA\books_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10%)
IF NOT EXISTS (SELECT name FROM sys.filegroups WHERE is_default=1 AND name = N'PRIMARY')
ALTER DATABASE [books] MODIFY FILEGROUP [PRIMARY] DEFAULT";
SqlCommand myCommand = new SqlCommand(str3, myConn);
myConn.Open();
myCommand.ExecuteNonQuery();
myConn.Close();
but i am getting the error:
Cannot open database “books” requested by the login. The login failed.
Login failed for user ‘Master-PC\Master’.
what can i do to solve this?
Well, reading your query it is clear that the books database doesn’t exist at the connection time. You try to create it with your query.
Change your connection string and connect to ‘master’ database
then execute your query, (this will create the database ‘books’), close the connection and reopen it with the original “InitialCatalog=books” string