Programmatically change SQL Server configuration - c#

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.

Related

C# Winforms connection to MySQL AWS Database

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();

SQL Server : CREATE DATABASE permission denied in database 'master'

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];

Unable to connect to any specified mysql C#

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

Programmatically creating a database (no permission?)

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.

Is there any difference between connection string for SQL server express and SQL server?

In my application, i make a dynamic connection string:
server = "Server = .\\" + this.comboBoxListInstances.SelectedItem.ToString() + ";";
connectionString = server + attachDatabase + databaseName + "Integrated Security = true";
On my laptop (using SQL server 2008 express), the result is:
// server = "Server = .\\SQLEXPRESS;" (I select SQLEXRESS in comboBox)
// attachDatabase = "AttachDbFileName = |DataDirectory|\\Resources\\DT.mdf;"
// databaseName = "Database = DATA;";
// so the conectionString is : "Server = .\\SQLEXPRESS;AttachDbFileName = |DataDirectory|\\Resources\\DT.mdf;Database = DATA;Integrated Security = true"
I read registry to find all SQL server Instances and let the user choose which they want.
This conectionString work fine on my laptop and my friend who use SQL server express too. However, when i run my app on another friend's laptop with SQL server 2008 R2 installed, it throws an exception:
It say the connection string is invalid, It is :
"Server = .\\MSSQLSERVER;AttachDbFileName = |DataDirectory|\\Resources\\DT.mdf;Database = DATA;Integrated Security = true"
when I try to temporarily disable comboBoxListInstance and use this conectionString
"Server = (local);AttachDbFileName = |DataDirectory|\\Resources\\DT.mdf;Database = DATA;Integrated Security = true"
The app works! So, I think there is a difference between the conection string for SQL server express and SQL server. Is it right? There is a question similar to mine here, and they say that there is no difference. If they are right, what is the problem of my connectionString?
P/S: sorry for my bad grammar
It looks like you just proved that SqlExpress installs its default named instance as "MSSQLSERVER" where as full sql installs an unnamed default instance of blank.
(local) means " .\ " " 127.0.0.1" WHATEVER instance is at 1433.
.MSSQLEXPRESS means explicitly .\MSSQLEXPRESS which may or may not be the (local) default instance.
As An Aside usually the most relevant difference at this point is that regular SQL will install with the ports open and TCP clients ready to go.
SQL Express will only allow local "dev" type of connections until you activate the external ports and client protocols.

Categories

Resources