How to use a SQL script to create a database in C#?

joshgom96

New member
Joined
Jun 27, 2020
Messages
1
Programming Experience
Beginner
Hi,

When my application starts up, I need it to first check if a database is created, if not, it will use an sql script to create one in Azure Data Studio.
How can I do this?
 
If you are using Entity Framework, look for the keywords "Entity Framework code first". Basically what happens is that Entity Framework of scripting creating the database if needed. It will also do schema upgrades if you have an older version of the schema and you have changed the "entities".

If you are not using Entity Framework, then you'll pretty much have to write all that code yourself. If you already have the SQL script for creating the database. then it's just a matter of just using ADO.NET to execute the script. Look at using SqlCommand.ExecuteNonQuery().
 
it will use an sql script to create one in Azure Data Studio.
No. Very much no. That's like say that your application would create a text file using Notepad. Notepad is an application for a human user to create, open, edit and save text files. If you're doing it in code, you're not using a separate GUI application to work with text files. Likewise, ADS is a GUI application for a human user to work with SQL Server databases. If your application is working with databases then it's not automating a GUI app to do it. It's connecting directly to the database server. Does your application use ADS to query the database? No, it would (assuming no ORM or the like sitting on top) use ADO.NET. That is how you connect to a database server and execute SQL code. It doesn't matter what that SQL code is, including CREATE DATABASE statements.

That said, if you actually have a file containing SQL commands then the easiest way to execute that is using OSQL, which is the SQL Server commandline utility. Just like any other external application, you can run OSQL using Process.Start. I'm not exactly sure what the requirements for OSQL are but if you have a local SQL Server instance then I would assume that you have OSQL.
 
Back
Top Bottom