I'm trying to programmatically create a new database (.mdf file) and eventually create tables inside the database. I'm not really sure what connection string to use, I saw the one in the code below thrown around a couple times on multiple sites. I'm getting an error while executing:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: CREATE DATABASE permission denied in database 'master'.
Below is the code that I'm running to create the database:
string filename = "C:\\AnalysisResultsDatabase.mdf";
string databaseName = Path.GetFileNameWithoutExtension(filename);
using (var connection = new SqlConnection("Server=localhost;Integrated security=SSPI;database=master"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = String.Format("CREATE DATABASE {0} ON PRIMARY (NAME={0}, FILENAME='{1}')", databaseName, filename);
command.ExecuteNonQuery();
command.CommandText = String.Format("EXEC sp_detach_db '{0}', 'true'", databaseName);
command.ExecuteNonQuery();
}
}
It could be caused by the SQL Server Instance service identity not having permissions to the location of the MDF file on disk.
Just for checking, try changing the service identity to LocalSystem (if it's not already set to that account).
Your domain account that you are logging into does not have the appropriate permissions for CREATE DATABASE. You'll have to contact an administrator who has enough permissions to grant them to you before you can create databases.
Related
I'm trying to establish a SqlConnection in my C# application, the application was working fine with Oracle DB but I wish to connect it to MS SQL now. I've made the necessary code changes which are mentioned in the code section below. The issue is SqlConnectionString,Open() throws exception
In web.config file I've added the CONNECTIONSTRING value as "Server=TCP:myServerName,Port_No\myInstanceName;Database=myDataBase;User Id=Username;Password=Password;"
private DataSet FireQuery(SqlCommand command, String tablename)
{
SqlConnection conn = new SqlConnection(CONNECTIONSTRING);
SqlDataAdapter adapter = new SqlDataAdapter();
conn.Open(); //Code throws exception here
command.CommandType = CommandType.Text;
command.Connection = conn;
adapter.SelectCommand = command;
DataSet ds = new DataSet();
adapter.Fill(ds, tablename);
conn.Close();
return ds;
}
Exception thrown is System.Data.SqlClient.SqlException:
Cannot open database "mydataBase" requested by the login. The login failed.
Login failed for user 'Username'.
The "cannot open database" error means the authentication succeeded but the database context could not be set. This indicates either database "myDataBase" does not exist on the instance (or is offline) or the user does not have permissions to use it. In the latter case, the script example below will allow the user to use the database and objects.
USE mydataBase;
--create a database user mapped to login of same name
CREATE USER Username;
--also GRANT permissions on objects used directly by application
GRANT SELECT ON TABLE dbo.YourTable TO Username;
Check the connection string in the config file (or wherever you are getting it and passing to "FireQuery". The Username or password is wrong.
Error is telling you that the username you are passing is "Username". Literally.
Are you sure it even exists an user with such a stupid username? (easy findable and bruteforceable)
Usually sql server connects with user "sa" or something like that, unless you create specific users on your own. I think you or someone else just copy pasted a connection string found in some online guide and didn't bothered to change username or password.
I am getting this error:
CREATE DATABASE permission denied in database 'master'.
An attempt to attach an auto-named database for file C:\APP_DATA\WRESTLING.MDF failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
but I give my service the administrator account:
So, why is it being denied?
Here is my code:
void ConnectToDb()
{
connStringBuilder = new SqlConnectionStringBuilder();
connStringBuilder.DataSource = #"(localdb)\MSSQLLocalDB";
connStringBuilder.InitialCatalog = "WRESTLING.MDF";
connStringBuilder.Encrypt = true;
connStringBuilder.ConnectTimeout = 30;
connStringBuilder.AsynchronousProcessing = true;
connStringBuilder.MultipleActiveResultSets = true;
connStringBuilder.IntegratedSecurity = true;
string temp = #"Server=EC2AMAZ-FN5N011\MSSQLSERVER;Database=C:\APP_DATA\WRESTLING.MDF;Trusted_Connection=True;";
string temp1 = #"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=C:\APP_DATA\WRESTLING.MDF;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
string temp2 = #"Data Source = (local); AttachDbFilename = C:\APP_DATA\WRESTLING.MDF; Integrated Security = True; Connect Timeout = 30;";
conn = new SqlConnection(temp2);
comm = conn.CreateCommand();
}
Also, I am using an IIS Service to connect to the SQL database and that IIS is an Administrator too .
Update:
[2
[3
Your code is the mix of connection strings to different servers. So it's not clear to which one you want to connect.
string temp and string temp2 attempt to connect to the default local instance of SQL Server. You should not attach nothing to it as there is already the database in question attached to this instance.
Your string temp1 attempts to connect to localdb, it's another server, not that one that we see on your screenshot, and here yes you can specify the file to attach.
Now it seems that you are trying to connect to the default instance under IIS APPPOOL\.NET v4.5 (your IIS is running under this account), this account is not the same with that you used to connect at the screenshot.
You should map this login to server (for now it's not mapped or at least not explicitely) and then map it to your database and make it db_owner:
create login [IIS APPPOOL\.NET v4.5] from windows;
use WRESTLING;
go
create user [IIS APPPOOL\.NET v4.5] from login [IIS APPPOOL\.NET v4.5];
exec sp_addrolemember 'db_owner', [IIS APPPOOL\.NET v4.5];
I want to backup database in SQL Server 2012 using this code:
BACKUP DATABASE aveed_co
TO DISK = 'C:\bakup.bak'
WITH FORMAT,
MEDIANAME = 'aveed_co',
NAME = 'aveed_co'
After execution this code in SQL Server Management Studio, I get this error:
Msg 233, Level 20, State 0, Line 0
A transport-level error has occurred when sending the request to the server.
(provider: Shared Memory Provider, error: 0 - No process is on the other end of the pipe.)
To solve this problem I must change log on type (in SQL Server configuration) as below:
In other hand I must change "log on as" from "Built-in account" (1) to "This account" (2).
When I change "log on as" to "This account" and enter username and password the SQL Server code execute correctly.
Note that I have permission to write on c: or any driver
Please help me to do this using C# or SQL Server code.
You do not have write permissions on drive C: for your custom user.
EDIT:
var query = #"BACKUP DATABASE [aveed_co]
TO DISK = 'C:\bakup.bak' WITH INIT
,NOUNLOAD
,NAME = N'aveed_co'
,NOSKIP
,STATS = 10
,NOFORMAT
,COMPRESSION";
using (var connection = new SqlConnection(#"Server=myServerAddress;Database=aveed_co;User Id=myUsername;Password=myPassword;"))
{
connection.Open();
using (var command = new SqlCommand(query, connection))
{
command.CommandTimeout = 0;
command.ExecuteNonQuery();
}
}
SQL Server must be able to read and write to the device; the account under which the SQL Server service runs must have write permissions.
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).
I'm encountering a problem with my database connection.
I started with a new blank solution, then I added a WCF library project, and last but not least a WCF website (service).
In the website i added a reference to the library where I have the interface (data contract), the class that implements the interface and the dataclasses.
what I'm trying to do is to connect to a database on a server and try to retrieve some data from there.
So the connection string looks like:
<add name="myConnectionString" connectionString="Data Source=MyServer; Initial Catalog=MyDatabase; User Id=me; Password=me123;" providerName="System.Data.SqlClient" />
and this is how I'm trying to connect with the database:
public List<string> GetEngagements(string id)
{
string sql = "SELECT myColumn FROM myTable WHERE Id = '" + id + "'";
string connString = string.Empty;
SqlConnection connDB;
connString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
connDB = new SqlConnection(connString);
SqlCommand command = new SqlCommand(sql, connDB);
connDB.Open();
SqlDataReader rdr = command.ExecuteReader();
List<string> numbers = new List<string>();
while (rdr.Read())
{
numbers.Add(rdr[0].ToString());
}
rdr.Close();
return numbers;
}
I'm getting an exception on connDB.Open().
Then exception message says:
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.
I've been getting this message for 2 days now, I've googled a lot and deleted the C:\Documents and Settings\username\Local Settings\Application Data\Microsoft\Microsoft SQL Server Data\SQLEXPRESS directory but it didn't work for me..
Any solution???? help please
The error message:
Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance.
Suggests that you're using user instancing, and therefore your connection string will point to an .mdf file on disk rather than the name of a database.
So I'll assume that you want to connect to a file instance rather than a server instance.
I'll also assume that you're using SqlExpress rather than the full fat version.
In which case your connection string is wrong. It should look more like this:
"Data Source=.\SQLEXPRESS;
AttachDbFilename=fileOnDisk.mdf;
Integrated Security=True;
User Instance=True;"
User instancing means that this server instance and the DB inside will only be visible to the application opening the connection string.
You don't have to use user instancing - you can set User Instance=False or just leave it out. Then once the application has made the connection you can connect other tools to the server instance and connect to the DB yourself.