Search code examples
c#data-transfersql-server-2008-express

How to input data into SQL Server for first time start of C# application


I created a C# program using SQL Server 2008 Express.

There is some data that must exist in the database table initially, for the C# application to run correctly.

I would like to transfer this data into the table the first time the C# application executes.

But I don't want this SQL data (record data) read from my C# code (I don't want to load this data from hard-coded C# code).

How does SQL Server store its record data, and how can I transfer the initial data into the database?


Solution

  • I'd try to not rely on a database being existent for your application to work. You're coupling yourself to the database which probably isn't a good idea. Do you think maybe you could execute a stored procedure from your application which would fill out the tables you're relying on? That way your DB creation code wouldn't exist in your application. This would however still mean your application is dependant on the database to function correctly.

    I would recommend one of two plans, the latter being the cleaner.

    Plan 1

    • Create a SQL script which will create and insert all the required data for the application to work and place this in a stored procedure
    • When your application starts first time it will check a configuration file to see if the program has ran before, if not, execute the stored procedure to create the required data
    • Alter an external configuration file (which could be password protected) which will indicate whether the stored procedure has already been run, could just be a simple bool
    • Each subsequent time the application runs it will check to see whether it's run before and won't execute the stored proc if it has

    Plan 2

    • Create a SQL script which will create and insert all the required data for the application to work and place this in a stored procedure
    • Use an installer to deploy your application with a custom action to create the database, explained here