Create a Database from Script Runtime - c#

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

Related

Take SQL database online/offline using 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.

how to talk to local databases?

I just added a new "local database" in my project using visual studio. Now I added the "New Data Source".
What I want to know is how you can do sql queries to the DB. I know how this is done in PHP but cant find good information about how to do this in C#. All I find is tutorials on how to drag detail or gridviews into the form.
I have one database called 'words' with three tables. I want to be able to do update queries to a row in each of these tables. something like this:
UPDATE easy SET words='blahblahblah' WHERE id=1;
How do you do this?
I am going to use SQL Server as example.
First you need to find out the connection string which should be similar to
_connectionString = "Data Source=(localdb)\\v11.0; Initial Catalog=words;Integrated Security=true;"
and then you do
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE easy SET words='blahblahblah' WHERE id=1;", connection))
{
cmd.ExecuteNonQuery();
}
}

Extract Table Meta-Data (description, fields and their data types)

I am implementing a C# application which should extract from the sql server the metadata for all tables in the specific database.
Such question was already asked - it was required to do that from sql -
SQL Server meta data table and column descrption .
I don`t want to run any queries.
Does C# has a API for that?
There is a following approach :
http://msdn.microsoft.com/en-us/library/ms254934(v=vs.110).aspx
Does the link above solve what I want to do?
In the example from the link - I get only one table? (but my requests is all database tables)as well where do I specify user credentials and database name?
Also I didn't find any reference about the performance of such execution?
For me it looks that it should be very effective to retrieve the schema if we really read only metadata from some source without executing a query
using (SqlConnection connection = new SqlConnection(#"Data Source=(local);Integrated Security=True;Initial Catalog=DB_Name;"))
{
connection.Open();
using (SqlCommand command = connection.CreateCommand()) {
command.CommandText =#"SELECT Name from Sysobjects where xtype = 'u'";
using (SqlDataReader reader = command.ExecuteReader()) {
while (reader.Read())
{
// your code goes here...
}
}
}
}`

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

Categories

Resources