Saturday, February 25, 2012

connection strings for "create database" queries

I'm using connection strings to SQL Server Express that have the form

"DataSource= .\SQLEXPRESS;AttachDbFilename="(path to my development directory)\CurrentDevelopmentDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"

I'm assuming this works because the DB is already there, created "manually".

How might I build a connection string for a SQLCommand for a "Create DataBase" query?

I'm confused about what the AttachDbFileName would be, or if there would be another variable in its place, since there's no file yet.

Any guidance on this would be appreciated.

Thanks!

Hi,

You use a connection string like the below sample connection string

Data Source=KODYAZ\SQLEXPRESS;Initial Catalog=ContentManager;Integrated Security=True

Eralper

http://www.kodyaz.com

|||

There are essentially 2 ways of connecting to SQL Server in the case that you are discussing(there are actually way more but bear with me I am trying to simplify this).

1/ Is to use User Instances, this is what you are doing, this allows you to use a DB that exists in the file system, it is temporarily attached to the SQL Server Service as a result of your connection being opened. SQL Server spins up a special user instance of SQL Server to attach the database to, rather than using the exisintg running instance.

2/ SQL Server is running and you connect to master (a system database) or one of the already attached user databases.

To decide which technique to use it depends on your application as the 2 are somewhat exclusive within an application. If you choose 2 then just use the following connecting string and the create database should work;

"DataSource= .\SQLEXPRESS;Initial Catalog=Master;Integrated Security=True;Connect Timeout=30"

To use the database you just created you must either change the initial catalog to it ina new connection, or issue a "use newdb" command in the current connection.

|||

Thanks for the inputs. I resolved this by creating the connection string with the "file path" method for an existing DB. Then I executed the SQL for the DB Create using that connection.

No comments:

Post a Comment