Create a SQL Server Database dynamically in C#

SQL provides statements to create new databases and database objects. You can execute these statements from your program to create databases programmatically.
In this article, I'll show you how to create a new SQL Server database and its objects such as a table, stored procedures, views and add and view data. I'll also show you how to change database table schema programmatically. You'll see how SQL statement ALTER TABLE is useful when you need to change a database table schema programmatically. 
 
Not only that, but this article also shows you how to view contents from a database table, stored procedures, and views.
 
SQL not only lets you select, add, and delete data from databases table, it also provides commands to manage databases. Using SQL statements you can create database objects programmatically such as a table, view, stored procedure, rule, index, and so on. It also provides commands to alter a database and database schemas for example adding and deleting a column from a database table, adding some constraints to a column, and so on. This example shows you how to create a new database table, add data to it, create a view of the data, alter the database table, and then delete the newly created table.
 
In this application, I'll create a SQL Server database, create a database table, add data to it, create database objects such as views, stored procedures, rules, and index and view data in the data grid using Sql data provider.
 
To test this application, create a Windows application adds a data grid control and some button controls. You can even test code by adding only one button or one button for each activity. Our application form looks like Figure 1.

CreatingDBProgrammaticallyMCB.jpg

Figure 1. Creating a database and it's object application.

After adding controls, add the following variables in the beginning of the form class.
  1. private string ConnectionString ="Integrated Security=SSPI;" +  
  2. "Initial Catalog=;" +  
  3. "Data Source=localhost;";  
  4. private SqlDataReader reader = null;   
  5. private SqlConnection conn = null;   
  6. private SqlCommand cmd = null;  
  7. private System.Windows.Forms.Button AlterTableBtn;  
  8. private string sql = null;  
  9. private System.Windows.Forms.Button CreateOthersBtn;  
  10. private System.Windows.Forms.Button button1;   
First thing I'm going to do is create ExecuteSQLStmt method. This method executes a SQL statement against the SQL Sever database (mydb which I will create from my program) using Sql data providers using ExecuteNonQuery method. The ExecuteSQLStmt method is listed in Listing 1.
 
Listing 1. The ExecuteSQLStmt method. 
  1. private void ExecuteSQLStmt(string sql)  
  2. {  
  3.     if (conn.State == ConnectionState.Open)  
  4.         conn.Close();  
  5.     ConnectionString = "Integrated Security=SSPI;" +  
  6.     "Initial Catalog=mydb;" +  
  7.     "Data Source=localhost;";  
  8.     conn.ConnectionString = ConnectionString;  
  9.     conn.Open();  
  10.     cmd = new SqlCommand(sql, conn);  
  11.     try  
  12.     {  
  13.         cmd.ExecuteNonQuery();  
  14.     }  
  15.     catch (SqlException ae)  
  16.     {  
  17.         MessageBox.Show(ae.Message.ToString());  
  18.     }  
  19. }  
After this, I'm going to create a new SQL Server database. The CREATE DATABASE SQL statement creates a database. The syntax of CREATE DATABASE depends on the database you create. Depending on the database type, you can also set values of database size, growth, and file name. Listing 2 creates a SQL Server database mydb and data files are stored in the C:\\mysql directory.
 
Listing 2. Creating a SQL Server database. 
  1. // This method creates a new SQL Server database  
  2. private void CreateDBBtn_Click(object sender, System.EventArgs e)  
  3. {  
  4.     // Create a connection  
  5.     conn = new SqlConnection(ConnectionString);  
  6.     // Open the connection  
  7.     if (conn.State != ConnectionState.Open)  
  8.         conn.Open();  
  9.     string sql = "CREATE DATABASE mydb ON PRIMARY"  
  10.     + "(Name=test_data, filename = 'C:\\mysql\\mydb_data.mdf', size=3,"  
  11.     + "maxsize=5, filegrowth=10%)log on"  
  12.     + "(name=mydbb_log, filename='C:\\mysql\\mydb_log.ldf',size=3,"  
  13.     + "maxsize=20,filegrowth=1)";  
  14.     ExecuteSQLStmt(sql);  
  15. }  
Now the next step is to create a table. You use CREATE TABLE SQL statement to create a table. In this statement, you define the table and schema (table columns and their data types). Listing 3 creates a table myTable with four-column listed in Table 1.
 
Table 1. New table myTable schema.
Column Name Type Size Property
myId integer 4 Primary Key
myName char  50  Allow Null
myAddress char 255 Allow Null
myBalance float 8 Allow Null 
Listing 4. Creating a database table.
  1. private void CreateTableBtn_Click(object sender, System.EventArgs e)  
  2. {  
  3.     // Open the connection  
  4.     if (conn.State == ConnectionState.Open)  
  5.         conn.Close();  
  6.     ConnectionString = "Integrated Security=SSPI;" +  
  7.     "Initial Catalog=mydb;" +  
  8.     "Data Source=localhost;";  
  9.     conn.ConnectionString = ConnectionString;  
  10.     conn.Open();  
  11.     sql = "CREATE TABLE myTable" +  
  12.     "(myId INTEGER CONSTRAINT PKeyMyId PRIMARY KEY," +  
  13.     "myName CHAR(50), myAddress CHAR(255), myBalance FLOAT)";  
  14.     cmd = new SqlCommand(sql, conn);  
  15.     try  
  16.     {  
  17.         cmd.ExecuteNonQuery();  
  18.         // Adding records the table  
  19.         sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) " +  
  20.         "VALUES (1001, 'Puneet Nehra', 'A 449 Sect 19, DELHI', 23.98 ) ";  
  21.         cmd = new SqlCommand(sql, conn);  
  22.         cmd.ExecuteNonQuery();  
  23.         sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) " +  
  24.         "VALUES (1002, 'Anoop Singh', 'Lodi Road, DELHI', 353.64) ";  
  25.         cmd = new SqlCommand(sql, conn);  
  26.         cmd.ExecuteNonQuery();  
  27.         sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) " +  
  28.         "VALUES (1003, 'Rakesh M', 'Nag Chowk, Jabalpur M.P.', 43.43) ";  
  29.         cmd = new SqlCommand(sql, conn);  
  30.         cmd.ExecuteNonQuery();  
  31.         sql = "INSERT INTO myTable(myId, myName, myAddress, myBalance) " +  
  32.         "VALUES (1004, 'Madan Kesh', '4th Street, Lane 3, DELHI', 23.00) ";  
  33.         cmd = new SqlCommand(sql, conn);  
  34.         cmd.ExecuteNonQuery();  
  35.     }  
  36.     catch (SqlException ae)  
  37.     {  
  38.         MessageBox.Show(ae.Message.ToString());  
  39.     }  
  40. }  
As you can see from Listing 5, I also add data to the table using INSERT INTO SQL statement.
 
The CREATE PROCEDURE statement creates a stored procedure as you can see in Listing 10-18, I create a stored procedure myPoc which returns data result of SELECT myName and myAddress column.
 
Listing 5. Creating a stored procedure programmatically. 
  1. private void CreateSPBtn_Click(object sender, System.EventArgs e)    
  2. {    
  3.     sql = "CREATE PROCEDURE myProc AS" +    
  4.     " SELECT myName, myAddress FROM myTable GO";    
  5.     ExecuteSQLStmt(sql);    
  6. }   
Now I show you how to create views programmatically using CREATE VIEW SQL statement. As you can see from Listing 6, I create a view myView which is the result of myName column rows from myTable.
 
Listing 6. Creating a view using CREATE VIEW
  1. private void CreateViewBtn_Click(object sender, System.EventArgs e)  
  2. {  
  3.     sql = "CREATE VIEW myView AS SELECT myName FROM myTable";  
  4.     ExecuteSQLStmt(sql);  
  5. }  
The ALTER TABLE is a useful SQL statement if you need to change your database schema programmatically. The ALTER TABLE statement can be used to add and remove new columns to a table, changing column properties, data types, and constraints. The Listing 7 shows that I change the database schema of myTable by first change column data type range from 50 to 100 characters and by adding a new column newCol of TIMESTAMP type.  
 
Listing 7. Using ALTER TABLE to change a database schema programmatically. 
  1. private void AlterTableBtn_Click(object sender, System.EventArgs e)    
  2. {    
  3.     sql = "ALTER TABLE MyTable ALTER COLUMN" +    
  4.     "myName CHAR(100) NOT NULL";    
  5.     ExecuteSQLStmt(sql);    
  6. }  
The new table schema looks like Table 2. 
 
Table 2. MyTable after ALTER TABLE
Column Name Type                Size                          Property
myId                     integer 4 Primary Key
myName char  50 Allow Null
myAddress char 255 Allow Null
myBalance  float 8 Allow Null
newCol timestamp  8 Allow Null
You can also create other database objects such as index, rule, and users. The code listed in Listing 8 creates one rule and index on myTable.
 
Note: Create an Index that can only create an index if you don't have an index on a table. Otherwise, you will get an error message. 
 
Listing 8. Creating rules and indexes using SQL statements. 
  1. private void CreateOthersBtn_Click(object sender, System.EventArgs e)  
  2. {  
  3.     sql = "CREATE UNIQUE CLUSTERED INDEX " +  
  4.     "myIdx ON myTable(myName)";  
  5.     ExecuteSQLStmt(sql);  
  6.     sql = "CREATE RULE myRule " +  
  7.     "AS @myBalance >= 32 AND @myBalance < 60";  
  8.     ExecuteSQLStmt(sql);  
  9. }  
The DROP TABLE command can be used to delete a table and its data permanently. The code listed in Listing 9 deletes myTable. 
 
Listing 9. Deleting table using DROP TABLE.
  1. private void DropTableBtn_Click(object sender, System.EventArgs e)    
  2. {    
  3.     string sql = "DROP TABLE MyTable ";     
  4.     ExecuteSQLStmt(sql);     
  5. }  
Now the next step is to view data from the table, view, and stored procedure. The ViewDataBtn_Click method listed in Listing 10 shows the entire data from the table. The ViewSPBtn_Click and ViewViewBtn_Click methods view the stored procedure and view the data we have created earlier. As you can see using views and stored procedures works the same as you use a SQL Statement. We have discussed working with Views and stored procedures at the beginning of this chapter. As you can see from Listing 10, 11, and 12, I view data from stored procedure and view.  
 
Listing 10. Viewing data from a database table.  
  1. private void ViewDataBtn_Click(object sender, System.EventArgs e)  
  2. {  
  3.     /// Open the connection  
  4.     if (conn.State == ConnectionState.Open)  
  5.         conn.Close();  
  6.     ConnectionString = "Integrated Security=SSPI;" +  
  7.     "Initial Catalog=mydb;" +  
  8.     "Data Source=localhost;";  
  9.     conn.ConnectionString = ConnectionString;  
  10.     conn.Open();  
  11.     // Create a data adapter  
  12.     SqlDataAdapter da = new SqlDataAdapter  
  13.     ("SELECT * FROM myTable", conn);  
  14.     // Create DataSet, fill it and view in data grid  
  15.     DataSet ds = new DataSet("myTable");  
  16.     da.Fill(ds, "myTable");  
  17.     dataGrid1.DataSource = ds.Tables["myTable"].DefaultView;  
  18. }  
Listing 11.Using a stored procedure to view data from a table.  
  1. private void ViewSPBtn_Click(object sender, System.EventArgs e)  
  2. {  
  3.     /// Open the connection  
  4.     if (conn.State == ConnectionState.Open)  
  5.         conn.Close();  
  6.     ConnectionString = "Integrated Security=SSPI;" +  
  7.     "Initial Catalog=mydb;" + "Data Source=localhost;";  
  8.     conn.ConnectionString = ConnectionString;  
  9.     conn.Open();  
  10.     // Create a data adapter  
  11.     SqlDataAdapter da = new SqlDataAdapter("myProc", conn);  
  12.     // Create DataSet, fill it and view in data grid  
  13.     DataSet ds = new DataSet("SP");  
  14.     da.Fill(ds, "SP");  
  15.     dataGrid1.DataSource = ds.DefaultViewManager;  
  16. }  
Listing 12.Using a view to view data from a table.  
  1. private void ViewViewBtn_Click(object sender, System.EventArgs e)  
  2. {  
  3.     /// Open the connection  
  4.     if (conn.State == ConnectionState.Open)  
  5.         conn.Close();  
  6.     ConnectionString = "Integrated Security=SSPI;" +  
  7.     "Initial Catalog=mydb;" +  
  8.     "Data Source=localhost;";  
  9.     conn.ConnectionString = ConnectionString;  
  10.     conn.Open();  
  11.     // Create a data adapter  
  12.     SqlDataAdapter da = new SqlDataAdapter  
  13.     ("SELECT * FROM myView", conn);  
  14.     // Create DataSet, fill it and view in data grid  
  15.     DataSet ds = new DataSet();  
  16.     da.Fill(ds);  
  17.     dataGrid1.DataSource = ds.DefaultViewManager;  
  18. }  
Finally, I create AppExit method which releases the connection and reader objects and I call them from the Dispose method as you can see in Listing 13. 
 
Listing 13. AppExit method 
  1. protected override void Dispose(bool disposing)  
  2. {  
  3.     AppExit();  
  4.     if (disposing)  
  5.     {  
  6.         if (components != null)  
  7.         {  
  8.             components.Dispose();  
  9.         }  
  10.     }  
  11.     base.Dispose(disposing);  
  12. }  
  13.   
  14. // Called when you are done with the application 
  15. // Or from Close button  
  16. private void AppExit()  
  17. {  
  18.     if (reader != null)  
  19.         reader.Close();  
  20.     if (conn.State == ConnectionState.Open)  
  21.         conn.Close();  
  22. }  

Summary

 
In this article, you saw how to create a new database and database objects including tables, stored procedures, views, and alter tables. You also saw how to delete these objects using SQL statements. 


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.