Take SQL database online/offline using C# - c#

Is there any way to take sql db online/offline programmatically using C#? I also noticed while database is offline, my C# program throws login failed exception.
my code:
var conn = CCULBCommon.Connection.connection("master");
conn.Open();
var sqlCmd = conn.CreateCommand();
sqlCmd.CommandText = string.Format(#"ALTER DATABASE {0} SET OFFLINE WITH ROLLBACK IMMEDIATE", dbName);
sqlCmd.CommandType = CommandType.Text;
conn.Close();

You can, there are 2 options
Connect to the master database and do ALTER DATABASE [DbName] SET ONLINE or ALTER DATABASE [DbName] SET OFFLINE WITH ROLLBACK IMMEDIATE
You can use SqlManagmentObjects and setup a connection with SMO and then you can use SetOffline or SetOnline. See this documentation on how to connect with SMO.

Related

Create a Database from Script Runtime

I have a T-SQL script to create a Database. I need to create this database runtime. When the application is Running.
What Connection String do I use?
How do I connect to the server and Create the Database? I am connecting to the server as a Network user. I am not using User "sa" I have a user "DBCreator"
My application is in C#.
I have this Script in T-SQL:
USE [master]
GO
CREATE DATABASE [XYZ]
-- Table Creation Code etc.
You can have two connection strings. One for master database to issue the CREATE DATABASE ... statement and another one for database created.
// You can use replace windows authentication with any user credentials who has proper permissions.
using (SqlConnection connection = new SqlConnection(#"server=(local);database=master;Integrated Security=SSPI"))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "CREATE DATABASE [XYZ]";
command.ExecuteNonQuery();
}
}
// Quering the XYZ database created
using (SqlConnection connection = new SqlConnection(#"server=(local);database=XYZ;Integrated Security=SSPI"))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "select * from sys.objects";
...
}
}
You can use the SMO objects to do that. I don't think i should explain what is already explained in details in a very good tutorial here
Definitely use SMO its intended to do everything that SSMS can do, and more! it actually has a command called Database.Create(), follow this MSDN page

Making a copy of an azure database

I need to make a copy of an azure database but I don't have access to any management tools, only a connection string.
I know that to use the CREATE DATABASE x AS COPY OF y command I need to be in the master database but I don't know how to tell Azure to run my command from there. For example, I have this code:
var commandText = "CREATE DATABASE foobar AS COPY OF " + database;
var connectionString = <my_connection_string>;
using (var conn = new SqlConnection(connectionString))
{
using (var cmd = new SqlCommand(commandText, conn))
{
cmd.CommandType = CommandType.Text;
conn.Open();
cmd.ExecuteNonQuery();
}
}
which fails with error "User must be in the master database" - as I expected.
However my connection string is not valid for the master database, so how do I execute this command from the master database? If I was in SQL Management Studio I would just do:
use master
CREATE DATABASE x AS COPY OF y
Is there any way of emulating that in my code?
Change your connection string to access the master database instead of your regular one. It's as simple as that and the only solution.

Creating a custom installer for occasionally connected application using database of another software

I am trying to create an application which will synchronize its database with another software's database..
Problems are:
How will the database will synchronize with external database after I have created the installer and installed..i.e. how will it take the connection string.
I am looking for a solution which will provide a button to select the required database and based on the selection automatically generate the connection string.
Is it possible to run SQL create queries on external database while installation after the database is selected via browse button?
You have an option to create a Connection Settings form, which will help user to construct the connection string.
Yes, it's possible. It looks something like this:
using (var sqlConnection = new SqlConnection(#"Data Source=myServerAddress;User Id=myUsername;Password=myPassword;"))
{
sqlConnection.Open();
string query = "CREATE DATABASE...";
using (var sqlCommand = new SqlCommand())
{
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = query;
sqlCommand.ExecuteNonQuery();
}
}
If it won't work, try to set Initial Catalog to master:
#"Data Source=myServerAddress;Initial Catalog=master;User Id=myUsername;Password=myPassword;"

How to detach database and copy db file in local device programmatically in C#

I want to detach the database from SQL Server 2005 from my C# code. I use the DROP query to detach. But it statements delete the file from my local system. I want to detach the database and copy that database in runtime.
First try to connect to the SQL Server without providing any database name,or path just like below:
ConnectionString = #"Data Source= YourDataSource ;Integrated Security=True;Connect Timeout=30";
Note:
YourDataSource can either be . or .\SQLEXPRESS or .\MSSQLSERVER or (local)\SQLEXPRESS or (localdb)\v11.0 or etc.
Then by using the following query, detach your database.
"ALTER DATABASE [your DB] SET OFFLINE WITH ROLLBACK IMMEDIATE \n\r exec sp_detach_db #dbname = [your DB]";
Ok.
My Sample code:
sql_connect1.ConnectionString = #"Data Source=.\sqlexpress;Integrated Security=True;Connect Timeout=30";
sql_command.CommandText = "ALTER DATABASE [IRAN] SET OFFLINE WITH ROLLBACK IMMEDIATE \n\r exec sp_detach_db #dbname = [IRAN]";
sql_command.Connection = sql_connect1;
sql_connect1.Open();
sql_command.ExecuteNonQuery();
sql_connect1.Close();
The SQL Server SMO API let's you do anything Sql Server management studio can do (from c# code).
Check out this link
http://msdn.microsoft.com/en-us/library/ms162175.aspx
you can detach a database on SqlServer by the following code:
There is a stored procedure in SqlServedr 'sp_detach_db' for detach a database, has one argument DataBaseName. Here in the code 'MyDatabase' is the database name you should change it with your database name
// C# Code
SqlConnection conn = new SqlConnection("Server=(local); Data Source=;Integrated Security=SSPI");
SqlCommand cmd = new SqlCommand("", conn);
cmd.CommandText = "sys.sp_detach_db MyDatabase";
conn.Open();
cmd.ExecuteNonQuery();
cmd.Dispose();
conn.Dispose();
You can use stored procedures for your problem. following link can be useful:
http://msdn.microsoft.com/en-us/library/aa259611.aspx
Myo Thu's comments lead me in the right direction, so here's a summary of steps on how to detach the database.
Step 1: Reference the following DLL's in your project [Reference]:
Microsoft.SqlServer.ConnectionInfo.dll
Microsoft.SqlServer.Smo.dll
Microsoft.SqlServer.Management.Sdk.Sfc.dll
Microsoft.SqlServer.SqlEnum.dll
Step 2: using:
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
Step 3: Code
var server = new Server(new ServerConnection(#"MyMachine\SQL2012"));
// Ensure database is not in use
server.KillAllProcesses("TestDatabase");
server.DetachDatabase("TestDatabase", true);
EDIT: Now documented in my blog here

While I connect to database using ADO.NET there is an error

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).

Categories

Resources