4. Working with SQL A database most often contains one or more tables. Each table is identified by a name (e.g. "Customers" or "Orders"). Tables contain records (rows) with data. Below is an example of a table called "Persons": LastName FirstName Address City Hansen Ola Timoteivn 10 Sandnes Svendson Tove Borgvn 23 Sandnes Pettersen Kari Storgt 20 Stavanger
5.
6.
7.
8.
9.
10. SQL Queries With SQL, we can query a database and have a result set returned. A query like this: SELECT LastName FROM Persons Gives a result set like this: LastName Hansen Svendson Pettersen
11.
12.
13. Selecting Data The SELECT statement is used to select data from a table. The tabular result is stored in a result table (called the result-set). Syntax SELECT column_name(s) FROM table_name
14. Select few columns To select the columns named "LastName" and "FirstName", use a SELECT statement like this: SELECT LastName, FirstName FROM Persons Persons LastName FirstName Address City Hansen Ola Timoteivn 10 Sandnes Svendson Tove Borgvn 23 Sandnes Pettersen Kari Storgt 20 Stavanger Result LastName FirstName Hansen Ola Svendson Tove Pettersen Kari
15.
16.
17. Conditions Used In Where Clause = equals > greater than < less than >= greater than or equal to <= less than or equal to <> not equal to
18.
19. Using Quotes Note that we have used single quotes around the conditional values in the examples. SQL uses single quotes around text values (most database systems will also accept double quotes). Numeric values should not be enclosed in quotes. For text values: This is correct: SELECT * FROM Persons WHERE FirstName='Tove' This is wrong: SELECT * FROM Persons WHERE FirstName=Tove
20.
21. Using LIKE The following SQL statement will return persons with first names that start with an 'O': SELECT * FROM Persons WHERE FirstName LIKE 'O%' The following SQL statement will return persons with first names that end with an 'a': SELECT * FROM Persons WHERE FirstName LIKE '%a' The following SQL statement will return persons with first names that contain the pattern 'la': SELECT * FROM Persons WHERE FirstName LIKE '%la%'
22. The INSERT INTO Statement The INSERT INTO statement is used to insert new rows into a table. Syntax INSERT INTO table_name VALUES (value1, value2,....) You can also specify the columns for which you want to insert data: INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....)
23. Insert a New Row And this SQL statement: INSERT INTO Persons VALUES ('Hetland', 'Camilla', 'Hagabakka 24', 'Sandnes') LastName FirstName Address City Pettersen Kari Storgt 20 Stavanger LastName FirstName Address City Pettersen Kari Storgt 20 Stavanger Hetland Camilla Hagabakka 24 Sandnes
24. Insert Data in Specified Columns And This SQL statement: INSERT INTO Persons (LastName, Address) VALUES ('Rasmussen', 'Storgt 67') LastName FirstName Address City Pettersen Kari Storgt 20 Stavanger Hetland Camilla Hagabakka 24 Sandnes LastName FirstName Address City Pettersen Kari Storgt 20 Stavanger Hetland Camilla Hagabakka 24 Sandnes Rasmussen Storgt 67
25.
26. The Update Statement The UPDATE statement is used to modify the data in a table. Syntax UPDATE table_name SET column_name = new_value WHERE column_name = some_value
27. Update one Column in a Row We want to add a first name to the person with a last name of "Rasmussen": UPDATE Person SET FirstName = 'Nina' WHERE LastName = 'Rasmussen' LastName FirstName Address City Nilsen Fred Kirkegt 56 Stavanger Rasmussen Storgt 67 LastName FirstName Address City Nilsen Fred Kirkegt 56 Stavanger Rasmussen Nina Storgt 67
28. The Delete Statement The DELETE statement is used to delete rows in a table. Syntax DELETE FROM table_name WHERE column_name = some_value
29. Delete a Row "Nina Rasmussen" is going to be deleted: DELETE FROM Person WHERE LastName = 'Rasmussen' LastName FirstName Address City Nilsen Fred Kirkegt 56 Stavanger Rasmussen Nina Stien 12 Stavanger LastName FirstName Address City Nilsen Fred Kirkegt 56 Stavanger
30. Delete All Rows It is possible to delete all rows in a table without deleting the table. This means that the table structure, attributes, and indexes will be intact: DELETE FROM table_name Or DELETE * FROM table_name
31.
Notes de l'éditeur
The DataReader was developed to get at data and in read-only forward-only fashion and provide the data as fast as possible to enable the developers as fast as possible. With the help of DataSet, it takes a snapshot of the data from database and storing this data offline for as long as necessary. When the end user using this copy of data he can persist the data and any changes to the data right back to data store.
Among the above 6 core namespaces ADO.NET classes are divided into three categories: Disconnected : These classes provides basic structure of ADO.NET includes DataTable, etc., The objects of this class are capable of storing data without any dependency on specific data provider. Shared: Set of base classes for data providers and shared among all data providers. Includes DataSet, DataRow, DataTable, Constraint, etc., Data Providers: These classes are meant to work with different data sources. Performs all database management operations on a specific database. Eg: SqlClient data provider works only with SQL Server Database.
ADO.NET ships with four database client namespaces. They are: System.Data.SqlClient System.Data.OracleClient System.Data.OleDb System.Data.Odbc. Within the .NET Framework data providers are light weight, creating minimal layer between the data source and code, increasing performance without scarifying functionality.
The SqlConnection Properties the DataSource, Database and State are read-only properties to read database server , database name and state of connection respectively.
Calling a stored procedure with a Command object is just assigning the stored procedure name to CommandText property of SqlCommand instance also setting the CommnadType property to CommandType.StoredProcedure value. Finally execute the one of previously stated method. The default ComandTimeout value is 30 seconds. The SqlRecord object contains only single returned row. When you begin transaction you can choose isolation level for commands executed within that transaction. This isolation levels specifies how changes made in one database session are viewed by another. These isolation levels are: ReadCommitted ReadUncomitted RepeatableRead Serializable ExecuteNonQuery() method is commonly user for UPDATE, INSERT or DELETE statements: This call will returns only the number of records effected. This call however can return results if you call a stored procedure that has output parameters.
While calling ExecuteMethod (i.e., ExecuteReader ) if you provide CommandBehavior.CloseConnection the connection will be automatically closed whenever you reached to end of the result set. In between if you want to close the connection you can call the Close() method on your Connection object.
While calling ExecuteMethod (i.e., ExecuteReader ) if you provide CommandBehavior.CloseConnection the connection will be automatically closed whenever you reached to end of the result set. In between if you want to close the connection you can call the Close() method on your Connection object.
SelectCommand: Gets or sets an object of type SqlCommand . This command is automatically executed to fill a DataTable with the result set. InsertComand: Gets or sets an object of type SqlCommand . This command used automatically executed to insert a new record to the database. UpdateCommand: Gets or sets an object of type SqlCommand . This command used to update the existing record on database. DeleteCommand: Gets or sets an object of type SqlCommand . Used to delete an existing record on database.
ParameterName: Gets or sets the name of the parameter SqlDbType: SQL server database type of the parameter value Size: Gets or sets the size of the parameter value. Direction: Gets or sets the direction of parameter such as input, output, or InputOutput . SourceColumn: Maps a column from a DataTable to the parameter. It enables you to execute multiple commands from SqlDataAdapter object and pick the correct parameter value from a DataTable column during the command execution. Value : Sets or gets the value provided by the parameter object. This value passed to the parameter defined in the command during the runtime.
Here links means primary key and Foreign key relation ships etc., In the above DataColumn instance we have given column name to CustomerID . If we don’t give there will be auto-generated column name(1, 2, .., ) is assigned by runtime. DataRow versions are described as: Current : The value existing at present column within the column. If no edit has occurred since received from database then it will be same as original value. Default: The default value. Original: The value of the column when originally selected from database. Proposed: When changes are proposed for a row it is possible to retrieve this modified value. (In between BeginEdit() and EndEdit() methods). Better guideline regarding DataSet is don’t use DataSet object unless your project required to work with multiple DataTable objects and you need a container for those objects. If you are working with single table then just use DataTable object rather then DataSet .
Better guideline regarding DataSet is don’t use DataSet object unless your project required to work with multiple DataTable objects and you need a container for those objects. If you are working with single table then just use DataTable object rather then DataSet . Server Explorer : In visual studio menu items select Data Generate Data Set;; It will creates Connection, adapter and xsd files. Using the DataAdapter : Open a connection Create a DataAdapter Finally Fill DataSet. To create DataSet programmatically: Define data column object Add DataColumn object to a DataTable Add DataTable object to a DataSet
If you select data from database and populating it with adapter class runtime automatically creates the schema for your DataTable. It is also possible to create a DataTable programmatically. So creating schemas programmatically. Finally .NET framework also supports for using XML schemas to define a DataSet class, DataTable class and other classes. In the above relationships means Primary key and Foreign key relationship between the columns of different tables. The key difference between DataSet class and old style hierarchical Recordset object is in the way relationship is presented. In Recordset object the relationship was presented was a pseudo-column within the row. This column itself was a Recordset object. The below constrains are enforced within a DataSet class if the EnforcedConstraints property of the DataSet is true. Cascade: If the parent key has been updated copy new key value to all child records. If the parent record has been deleted then delete all the child records also. None: No action in child records whatsoever. This option leaves orphand rows within the child data table. SetDefault: Each child record affected has the foreign key column set to its default value if one has defined. SetNull: All child rows have the key column set to DBNull.
If you are working on a single table just use DataTable instead of DataSet. If you are working with multiple table and you need container for those tables to make relations use DataSet . To load the data from DataReader to DataTable just call Load() method on DataTable . SqlDataReader myReader = cmd.ExecuteReader(..); DataTable myTable = new DataTable(); myTable.Load(myReader); In reverse if you want a reader from DataTable then use: DataTableReader myReader = myTable.CreateDataReader();