3

I'm creating a system using SQL Server 2012 for database, but when this system is starting first time in a computer, I want the system create the database and tables for me no create this manual.

How to I create database with C#? And how to I set connect string? because normally I set database name in the connect string, but now, I need create database before

6
  • 1
    Too broad. Close-voting. Check the documentation Commented Sep 16, 2013 at 15:09
  • Use EntityFrameWork codefirst Commented Sep 16, 2013 at 15:10
  • How are you distributing the program, Are you using an installer, click-once, or are you just copying the compiled exe to the computer? Also how are you accessing the database, if you are using EntityFramework it has things built in to create the database for you but if you are just using ADO.net you may need a setup script. Commented Sep 16, 2013 at 15:10
  • @ScottChamberlain I wanted just copying the compiled exe to the computer Commented Sep 16, 2013 at 15:13
  • @RaimondKuipers I will study about this, thank you so much Commented Sep 16, 2013 at 15:13

1 Answer 1

6

You can use SQL script, leave database name empty. Example code here :

static void Main(string[] args)
{
  using (var conn = new SqlConnection("data source=DBServer; uid=UserName; pwd=Password;"))
  {
    using (var cmd = new SqlCommand())
    {
      conn.Open();
      cmd.Connection = conn;
      cmd.CommandText = "Create Database NewDB;";
      cmd.ExecuteNonQuery();
      cmd.CommandText = "Use NewDB;CREATE TABLE dbo.Table1 (ID int, Data nvarchar(128));";
      cmd.ExecuteNonQuery();
    }
  }
}
Sign up to request clarification or add additional context in comments.

7 Comments

Sorry, I had try it, but it's not working, I had change DBServer for localhost, uid=sa; pwd=admin, but it's not working
You cannot use USE <dbName> in the same batch as another command. I'd suggest closing the connection after you create the DB, and then re-open it specifying the new DB in the connection string.
@RBarryYoung - your movin sql page is hosed.
@RBarryYoung I tried on SQL Server 2008 R2 and it's working, do you have any reference that this cannot be used in the same connection ?
@Lai32290 can you write any thing more about how is this not working ? Does it connect to db ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.