Tuesday, March 20, 2012

Accessing a database file

Hi,

I'm a hobby C# programmer, and when at university there are a few machines that have SQL Server 2005 installed on them (i think it's standard ed).

From looking around at sql 2005 free edition and DNN (dot net nuke) it's apparently possible to have the database file in the execution directory of your application.

My question is this, if i have a C# win app, is in possible for me to store the database files, in the executable directory of that app, and not in the default sql database store of C:\prog files\sql server\90\ data etc...?

Ie, what i want to do, is for the C# win application on start up to "mount" the database, use it normally like any other sql database, and then "unmount" it at the end.

The reason for "mounting" and "unmounting" is that i don't want the database to be accessible or even visible to sql server when the c# app isnt running.

I hope I've explained myself clearly, and thanks a lot in advance.
pro-logic

Yes you can have the database file in the application directory with the SQL Server Express system, this is called a User Instance and the databases are attached at run time by the application using some values in the connection string. The easy way to test this is to fire up a new Windows Application and select add a new item... From there add a database file and follow the wizard. Now if you create some database objects in the database and then connect them using a dataset (Using the wizard of course) the application will make an app.config file and stiore the connection string there for you. You should then be able to see what the code for the connection string would look like.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

<configSections>

</configSections>

<connectionStrings>

<add name="Call4Help.Properties.Settings.Call4HelpConnectionString"

connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database\Database.mdf;Integrated Security=True;User Instance=True"

providerName="System.Data.SqlClient" />

</connectionStrings>

</configuration>

|||Cool, Thanks a lot for your answer!

A follow up question, will this work on a non-sql express version of SQL as well?

No comments:

Post a Comment