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];
Related
I'm trying to connect a winforms .net application with an AWS RDS MySQL database but I am having difficulty making the connection. I have read a lot of material about connecting through Microsoft SQL database and through Elastic Beanstalk but I haven't come across the answer I'm looking for... possibly because I'm a noob.
I've looked through a few of these questions:
How to connect to MySQL Database?
https://dev.mysql.com/doc/dev/connector-net/8.0/html/T_MySql_Data_MySqlClient_MySqlConnection.htm
using MySql.Data.MySqlClient;
string connection = "server=localhost; Database=database_URL; User Id=admin;
Password=myPassword";
myConn.Open();
MessageBox.Show("Success");
I'm getting the following error message:
MySql.Data.MySqlClient.MySqlException: 'Unable to connect to any of the specified MySQL hosts.'
Is there something simple that I'm missing? I have copied the database endpoint into the database_URL location. My user id and password are correct. My database is setup on AWS as a MySQL database.
Checking back with ConnectionStrings makes it appear as if your parameter-names are wrong. 'username' should be 'uid' and 'password' should be 'pw'.
In any case I'd suggest using the MySqlConnectionStringBuilder-class to construct your connection string.
var connectionStringBuilder = new MySqlConnectionStringBuilder
{
Server = "<Instance_Ip>",
UserID = "root",
Password = "<Password>",
Database = "<Database_Name>"
};
using (var conn = new MySqlConnection(connectionStringBuilder.ToString()))
The error message is given because can't connect to the host.
In your connection string is given the localhost as the server but your database is on cloud (AWS), so it means that you must specify the database's IP or the domain name pointing to that database, not the local (local means that is in your computer). e.g.
string conn = "server=192.168.0.7; Database=database_name; User Id=admin;
Password=myPassword";
Note that the server IP is provided by AWS, and you'd make sure that ports are enable. The most common port for MySQL is 3306.
Best regards.
Try this,
//This is my connection string i have assigned the database file address path
string MyConnection2 =
"host='localhost';database='databasename';username='myusername';password='mypassword'";
//This is my insert query in which i am taking input from the user through windows forms
string Query = "Your query";
//This is MySqlConnection here i have created the object and pass my connection string.
MySqlConnection MyConn2 = new MySqlConnection(MyConnection2);
//This is command class which will handle the query and connection object.
MySqlCommand MyCommand2 = new MySqlCommand(Query, MyConn2);
MySqlDataReader MyReader2;
MyConn2.Open();
MyReader2 = MyCommand2.ExecuteReader();
// Here our query will be executed and data saved into the database.
MessageBox.Show("Save Data");
while (MyReader2.Read())
{
}
MyConn2.Close();
I can't connect to my sql server, i tried some fixes from stackoverflow and google and it didn't help me. Thanks.
connString = "SERVER ='''myserverip''';PORT=3306;DATABASE=mydatabase;UID=myuser;PASSWORD=mypassword";
try
{
conn = new MySqlConnection();
conn.ConnectionString = connString;
conn.Open();
MessageBox.Show("Connection success");
}
catch (MySql.Data.MySqlClient.MySqlException ex)
{
MessageBox.Show(ex.Message);
}
To configure myuser I used this on my linux vps.
CREATE USER 'myuser'#'localhost' IDENTIFIED BY 'mypassword'; CREATE USER 'myuser'#'%' IDENTIFIED BY 'mypassword'; GRANT ALL ON *.* TO 'myuser'#'localhost'; GRANT ALL ON *.* TO 'myuser'#'%';
i tried : Unable to connect to any of the specified mysql hosts. C# MySQL ( i tried to use MySqlConnectionStringBuilder, don't specify the port, instead of password in connection string i typed psw);
Disable my pc firewall, disable linux server firewall
MySqlConnectionStringBuilder does enable you to specify port. Just tested, this works just fine:
MySqlConnectionStringBuilder csb = new MySqlConnectionStringBuilder();
csb.Server = "192.168.1.105";
csb.Port = 3307;
csb.Database = "test";
csb.UserID = "me";
csb.Password = "mypassword";
cn = new MySqlConnection(csb.ToString());
cn.Open();
Are you quite sure your MySql server actually accepts incoming connections over TCP? By default that is disabled.
So, after searching on google how to setup sql connection in linux, and trying different setups hardly I fixed it so I want to share with stackoverflow how I fixed it. Thanks for help #Avo Nappo.
First you need to comment out the line #bind-address from your sql config.
The accepted answer here :MySQL root access from all hosts .
Then I create a user using this command CREATE USER 'golden'#'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'golden'#'%';
And in c# I used my default connection string that is in the question. I don't know why but MySqlConnectionStringBuilder dose not work on my pc. I hope this will help someone. Have a nice day and keep coding.
You must go in your Remote MySQL in your C-Pannel and Add Access Host first and change this code
connString = "SERVER ='''myserverip''';PORT=3306;DATABASE=mydatabase;UID=myuser;PASSWORD=mypassword";
to
connString = "SERVER =*Put here your Hostname with Port*;DATABASE=mydatabase;UID=myuser;PASSWORD=mypassword;";
Or use this Method
MySqlConnectionStringBuilder ConStD = new MySqlConnectionStringBuilder();
ConStD.Server = "Hostname that get from Manage Access Hosts";
ConStD.Port = Port that get from Manage Access Hosts;
ConStD.Database = "YourDatabaseName";
ConStD.UserID = "yourUsername";
ConStD.Password = "yourpassword";
try
{
MySqlConnection conn = new MySqlConnection(ConStD.ToString());
conn.Open();
MessageBox.Show("connection Success");
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
It's Must working For You
1-Un check all Firewall and Network protection settings
2-Go in database management system running icon like wamp green icon
3-Go to Mysql CMD
3a-
CREATE USER 'muzamil'#'%' identified by 'muzamil';
grant all privileges on *.* to 'muzamil'#'%';
flush privileges;
These three commands run one by one
4-Windows Defender Firewall
then Click on Advance settings
==> Inbound Rules
->Enable riles Remote Desktop TCP All Rules
5:
C:\wamp64\alias
open this File then
change local to
==> Require all granted
==> Allow from all
Your remote server
will work with c# application
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.
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.
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.