using System; using System.Drawing; using System.Windows.Forms; using System.Data.SqlClient; public class Exercise : System.Windows.Forms.Form { Button btnDatabase; public Exercise() { InitializeComponent(); } void InitializeComponent() { btnDatabase = new Button(); btnDatabase.Text = "Database"; btnDatabase.Location = new Point(12, 12); btnDatabase.Click += new EventHandler(btnDatabaseClick); Controls.Add(btnDatabase); } void CreateDatabase() { using (SqlConnection connection = new SqlConnection("Data Source=(local);" + "Integrated Security=SSPI;")) { SqlCommand command = new SqlCommand("CREATE DATABASE VideoCollection1 " + "ON PRIMARY " + "( NAME = VideosRepository, FILENAME = 'C:\\VideoCollection\\Video1.mdf') " + "LOG ON " + "( NAME = VideosLog, FILENAME = 'C:\\VideoCollection\\Video1.ldf');", connection); connection.Open(); command.ExecuteNonQuery(); MessageBox.Show("A database named VideoCollection1 has been created.", "Video Collection", MessageBoxButtons.OK, MessageBoxIcon.Information); } using (SqlConnection connection = new SqlConnection("Data Source=(local);" + "Database='VideoCollection1';" + "Integrated Security=yes;")) { SqlCommand command = new SqlCommand("CREATE TABLE Videos(" + "Title nvarchar(80), " + "CopyrightYear smallint, " + "Length nvarchar(30), " + "Rating nvarchar(6), " + "WideScreen bit);", connection); connection.Open(); command.ExecuteNonQuery(); MessageBox.Show("A table named \"Videos\" has been created.", "Video Collection", MessageBoxButtons.OK, MessageBoxIcon.Information); } } void btnDatabaseClick(object sender, EventArgs e) { CreateDatabase(); } public static int Main() { System.Windows.Forms.Application.Run(new Exercise()); return 0; } } Because a table is the central part of a database, the information it holds must be meticulously organized. To better manage its information, data of a table is arranged in a series of cells. Once a table contains information, you can review it using either the Microsoft SQL Server Management Studio or a Windows application.
Data Navigation consists of displaying and viewing data. Because information of a database is stored in tables, your primary means of viewing data consists of opening a table in a view that displays its information. When a table displays its records, you navigate through its fields using the mouse or the keyboard. With the mouse, to get to any cell, you can just click it. To navigate through records using the keyboard, you can press:
As you are probably aware already, columns are used to organize data by categories. Each column has a series of fields under the column header. One of the actual roles of a table is to display data that is available for each field under a particular column. Data entry consists of providing the necessary values of the fields of a table. Data is entered into a field and every time this is done, the database creates a row of data. This row is called a record. This means that entering data also self-creates rows. There are various ways you can perform data entry for a Microsoft SQL Server table:
Probably the easiest and fastest way to enter data into a table is by using either Microsoft SQL Server Management Studio or Microsoft Visual Studio. Of course, you must first open the desired table from a database connection. In the Server Explorer, after expanding the connection to the database and the Tables nodes, right-click the desired table and click Show Table Data. If the table does not contain data, it would appear with one empty row. If some records were entered already, their rows would show and the table would provide an empty row at the end, expecting a new record. To perform data entry on a table, you can click in a cell. Each column has a title, called a caption, on top. This gray section on top is called a column header. In Microsoft SQL Server, it displays the actual name of the column. You refer to the column header to know what kind of data should/must go in a field under a particular column. This is why you should design your columns meticulously. After identifying a column, you can type a value. Except for text-based columns, a field can reject a value if the value does not conform to the data type that was set for the column. This means that in some circumstances, you may have to provide some or more explicit information to the user.
To perform data entry using SQL, use the INSERT combined with the VALUES keywords. The primary statement uses the following syntax: INSERT TableName VALUES(Column1, Column2, Column_n); Alternatively, or to be more precise, you can use the INTO keyword between the INSERT keyword and the TableName factor to specify that you are entering data in the table. This is done with the following syntax: INSERT INTO TableName VALUES(Column1, Column2, Column_n) The TableName factor must be a valid name of an existing table in the database you are using. If the name is wrong, the SQL interpreter would simply consider that the table you are referring to doesn't exist. Consequently, you would receive an error. The VALUES keyword indicates that you are ready to list the values of the columns. The values of the columns must be included in parentheses. If the column is a BIT data type, you must specify one of its values as 0 or 1. If the column is a numeric type, you should pay attention to the number you type. If the column was configured to receive an integer (int, bigint, smallint), you should provide a valid natural number without the decimal separator. If the column is for a decimal number (float, real, decimal, numeric), you can type the value with its character separator (the period for US English). If the column was created for a date or time data type (datetime or smalldatetime), make sure you provide a valid date. If the data type of a column is a string type, you should include its entry between single quotes. For example, a shelf number can be specified as 'HHR-604' and a middle initial can be given as 'D'. In your Windows Forms Application, you can pass the INSERT statement to a command object.
The most common technique of performing data entry requires that you know the sequence of fields of the table in which you want to enter data. With this subsequent list in mind, enter the value of each field in its correct position. Here is an example: void CreateRecord() { using (SqlConnection connection = new SqlConnection("Data Source=(local);" + "Database='VideoCollection1';" + "Integrated Security=yes;")) { SqlCommand command = new SqlCommand("INSERT INTO Videos " + "VALUES(N'A Few Good Men', 1992, N'138 Minutes', N'R', 0);", connection); connection.Open(); command.ExecuteNonQuery(); MessageBox.Show("A new record has been created.", "Video Collection", MessageBoxButtons.OK, MessageBoxIcon.Information); } } During data entry on adjacent fields, if you do not have a value for a numeric field, you should type 0 as its value. For a string field whose data you do not have and cannot provide, type two single-quotes '' to specify an empty field.
The adjacent data entry we have performed requires that you know the position of each column. The SQL provides an alternative that allows you to perform data entry using the name of a column instead of its position. This allows you to provide the values of columns in an order of your choice. We have just seen a few examples where the values of some of the fields were not available during data entry. Instead of remembering to type 0 or NULL for such fields or leaving empty quotes for a field, you can use the fields' names to specify the fields whose data you want to provide. To perform data entry in an order of your choice, you must provide your list of the fields of the table. You can either use all columns or provide a list of the same columns but in your own order. In the same way, you don't have to provide data for all fields, just those you want, in the order you want. Here are examples: void RandomlyCreateRecords() { using (SqlConnection connection = new SqlConnection("Data Source=(local);" + "Database='VideoCollection1';" + "Integrated Security=yes;")) { SqlCommand command = new SqlCommand("INSERT INTO Videos(Title, CopyrightYear, Length) " + "VALUES(N'Silence of the Lambs (The)', 1991, N'118 Minutes'); " + "INSERT INTO Videos(Title, WideScreen, Length) " + "VALUES(N'Distinguished Gentleman (The)', 0, N'112 Minutes'); " + "INSERT INTO Videos(Title, Length, WideScreen) " + "VALUES(N'Lady Killers (The)', N'104 Minutes', 0); " + "INSERT INTO Videos(Title, Length) " + "VALUES(N'Ghosts of Mississippi', N'130 Minutes');", connection); connection.Open(); command.ExecuteNonQuery(); MessageBox.Show("A few records have been created.", "Video Collection", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
In previous sections, we added one record at a time. You can add various records with one call to INSERT. If you are adding a value to each column of the table, after the name of the table, type VALUES, open and close the first parentheses. Inside the parentheses, include the desired values. To add another record, type a comma after the closing parenthesis, open a new parenthesis, list the new values, and close the parenthesis. Do this as many times as you need to add records. Here is an example: void CreateMultipleRecords() { using (SqlConnection connection = new SqlConnection("Data Source=(local);" + "Database='VideoCollection1';" + "Integrated Security=yes;")) { SqlCommand command = new SqlCommand("INSERT INTO Videos " + "VALUES(N'Her Alibi', 1998, N'94 Minutes', N'PG-13', 0), " + " (N'Memoirs of a Geisha', 2006, N'145 Minutes', N'PG-13', 1), " + " (N'Two for the Money', 2008, N'2 Hrs. 3 Mins.', N'R', 1);", connection); connection.Open(); command.ExecuteNonQuery(); MessageBox.Show("Records have been added to the Videos table.", "Video Collection", MessageBoxButtons.OK, MessageBoxIcon.Information); } } This is valid for adjacent data entry. If you want to follow your own order of columns, on the right side of the name of the table, include a list of columns in parentheses. Then, when giving the values, for each record, follow the order in which you listed the columns. Here is an example: void CreateVariousRecords() { using (SqlConnection connection = new SqlConnection("Data Source=(local);" + "Database='VideoCollection1';" + "Integrated Security=yes;")) { SqlCommand command = new SqlCommand("INSERT INTO Videos(Rating, Title, Length) " + "VALUES(N'R', N'Wall Street', N'126 Minutes')," + " (N'', N'Michael Jackson Live in Bucharest', N'122 Minutes')," + " (N'PG-13', N'Sneakers', N'2 Hrs. 6 Mins.')," + " (N'R', N'Soldier', N'99 Mins.');", connection); connection.Open(); command.ExecuteNonQuery(); MessageBox.Show("Four records have been added to the Videos table.", "Video Collection", MessageBoxButtons.OK, MessageBoxIcon.Information); } } In the techniques we have used so far, when or if the records were added to a table, whether the operation was successful or not, we had no way of finding out. One way you can get this information is to store the inserted records in another table. To support this, Transact-SQL provides the OUTPUT operator. The formula to use it is: INSERT INTO TableName OUTPUT INSERTED.Columns VALUES(Value_1, Value_2, Value_X) You start with the normal record insertion with the INSERT INTO TableName expression. This is followed by the OUTPUT operator followed by the INSERTED operator and a period. If you are adding a value for each record, follow the period with *. The statement continues with the VALUES operator that is followed by parentheses in which you list the values to be added to the table. Here is an example: USE Exercise1; GO CREATE TABLE Videos ( Title nvarchar(50), CopyrightYear smallint, Length nvarchar(30), Rating nvarchar(6), WideScreen bit ) GO INSERT INTO Videos OUTPUT inserted.* VALUES(N'Platoon', 1986, N'120 Minutes', N'R', 1), " + (N'Armageddon', 1998, N'150 Mins', N'PG-13', 0), " + (N'People vs. Larry Flynt (The)', 1996, N'129 Minutes', N'R', 0);",; GO When this statement executes, if you are working in the Microsoft SQL Server Management Studio, the lower part would display a list of the records that were added. If you use the above formula, when you close the database, the reference is lost. If you want to store the list of newly created records in a table, on the right side of the INSERTED operator and its period, type INTO followed by the name of the table that will receive the values. The table must have been created; that is, it must exist at the time this insertion operation is taking place. Here is an example: void KeepAnArchiveOfRecordsCreated() { using (SqlConnection connection = new SqlConnection("Data Source=(local);" + "Database='VideoCollection1';" + "Integrated Security=yes;")) { SqlCommand command = new SqlCommand("CREATE TABLE Archives(" + "Title nvarchar(50)," + "CopyrightYear smallint," + "Length nvarchar(30)," + "Rating nvarchar(6)," + "WideScreen bit);", connection); connection.Open(); command.ExecuteNonQuery(); MessageBox.Show("To keep an archive of records added to the Videos, " + "a table named Archives has been created.", "Video Collection", MessageBoxButtons.OK, MessageBoxIcon.Information); } using (SqlConnection connection = new SqlConnection("Data Source=(local);" + "Database='VideoCollection1';" + "Integrated Security=yes;")) { SqlCommand command = new SqlCommand("INSERT INTO Videos " + "OUTPUT inserted.* INTO Archives " + "VALUES(N'Platoon', 1986, N'120 Minutes', N'R', 1), " + " (N'Armageddon', 1998, N'150 Mins', N'PG-13', 0), " + " (N'People vs. Larry Flynt (The)', 1996, N'129 Minutes', N'R', 0);", connection); connection.Open(); command.ExecuteNonQuery(); MessageBox.Show("A few records have been created.", "Video Collection", MessageBoxButtons.OK, MessageBoxIcon.Information); } } In this case, a copy of the newly created records would be stored in the indication table. The above techniques assume that you are adding a complete record; that is, you are providing a value for each column of the table. We already saw that if you want to provide values for only some columns, after the name of the table, provide the list of columns in parentheses. To get the list of newly inserted records, after the OUTPUT keyword, type INSERTED followed by a period and followed by the name of the first column. Do this for each column. The formula to use is: INSERT INTO TableName(Column_1, Column_2, Column_X) OUTPUT INSERTED.Column_1, INSERTED.Column_2, INSERTED.Column_X VALUES(Value_1, Value_2, Value_X) Of course, you can list the columns in an order of your choice, as long as both the TableName and the OUTPUT section use the exact same order. Here is an example: SqlCommand command = new SqlCommand("INSERT INTO Videos(CopyrightYear, Rating, Title)" + "OUTPUT inserted.CopyrightYear, inserted.Rating, inserted.Title " + "VALUES(1995, N'R', N'Bad Boys')," + " (2007, N'PG-13', N'Transformers');", . . . In this case, when the statement has executed, the result would display in the lower portion of the Microsoft SQL Server Management Studio. If you want to store the result in a table, use the following formula INSERT INTO TableName(Column_1, Column_2, Column_X) OUTPUT INSERTED.Column_1, INSERTED.Column_2, INSERTED.Column_X INTO TargetTable VALUES(Value_1, Value_2, Value_X) Here is an example: void CreateAndArchive()
{
using (SqlConnection connection =
new SqlConnection("Data Source=(local);" +
"Database='VideoCollection1';" +
"Integrated Security=yes;"))
{
SqlCommand command =
new SqlCommand("INSERT INTO Videos(CopyrightYear, Rating, Title)" +
"OUTPUT inserted.CopyrightYear, inserted.Rating, inserted.Title " +
"INTO Archives (CopyrightYear, Rating, Title)" +
"VALUES(1995, N'R', N'Bad Boys')," +
" (2007, N'PG-13', N'Transformers');",
connection);
connection.Open();
command.ExecuteNonQuery();
MessageBox.Show("New records have been created and archived.",
"Video Collection",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||