DB Tables From C-Sharp
DB Tables From C-Sharp
2. Place a button on Form1. Change the button's Name property to btnCreateDatabase, and then change the
3. Use the using statement on the System and System.Data namespaces so that you do not have to qualify
declarations in those namespaces later in your code. Add the following code to the General Declarations
section of Form1:
4.using System;
5.using System.Data.SqlClient;
6. Switch to Form view, and then double-click Create Database to add the click event handler. Add the following
7. String str;
8. SqlConnection myConn = new SqlConnection ("Server=localhost;Integrated
security=SSPI;database=master");
9.
10. str = "CREATE DATABASE MyDatabase ON PRIMARY " +
11. "(NAME = MyDatabase_Data, " +
12. "FILENAME = 'C:\\MyDatabaseData.mdf', " +
13. "SIZE = 2MB, MAXSIZE = 10MB, FILEGROWTH = 10%) " +
14. "LOG ON (NAME = MyDatabase_Log, " +
15. "FILENAME = 'C:\\MyDatabaseLog.ldf', " +
16. "SIZE = 1MB, " +
17. "MAXSIZE = 5MB, " +
18. "FILEGROWTH = 10%)";
19.
20. SqlCommand myCommand = new SqlCommand(str, myConn);
21. try
22. {
23. myConn.Open();
24. myCommand.ExecuteNonQuery();
25. MessageBox.Show("DataBase is Created Successfully", "MyProgram",
MessageBoxButtons.OK, MessageBoxIcon.Information);
26. }
27. catch (System.Exception ex)
28. {
29. MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButtons.OK,
MessageBoxIcon.Information);
30. }
31. finally
32. {
33. if (myConn.State == ConnectionState.Open)
34. {
35. myConn.Close();
36. }
37. }
38. Change the connection string to point to your computer running SQL Server, and then verify that the Database
39. Press F5 or CTRL+F5 to run the project, and then click Create Database.
40. Use the Server Explorer to verify that the database is created.
NOTES:
The folder that is going to hold the created .mdf and .ldf files must already exist before you run the code or an
If you want to create a database that is similar to the SQL Server Model database, and you want the database in
the default location, then change the str variable in the code, as in the following sample code:
Not only that, this article also shows you how to view contents from a database table, stored procedures
and views.
SQL not only let 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 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 Widows application add 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.
After adding controls, add the following variables in the beginning of the form class.
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.
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.
Now 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.
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 returs data result of SELECT myName and myAddress column.
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 result of myName column rows from myTable.
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 show 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.
You can also create other database object such as index, rule, and users. The code listed in Listing 8
creates one rule and index on myTable.
Note: Create Index can only create an index if you don't have an index on a table. Otherwise you will get
an error message.
The DROP TABLE command can be used to delete a table and its data permanently. The code listed in
Listing 9 deletes myTable.
Now 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 stored procedure and view data we have created earlier. As you can see using views and
stored procedures work same as you use a SQL Statement. We have discussed working with Views and
stored procedures in the beginning of this chapter. As you can see from Listing 10, 11, and 12, I view data
from stored procedure and view.
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.
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 object using SQL statements.