ADO.net
ADO.net
Quick
Reference
- 1-
procedures
Chapter 1
Database Overview
Overview
_
A Database is an organized collection of information that is divided into tables. Each table is further divided into rows and columns; these columns store the actual information. _ You access a database using Structured Query Language (SQL), which is a standard language supported by most database software including SQL Server, Access, and Oracle. Query operations are divided into three different categories Data Definition Language (DDL) _ _ Commands are used to create and manage the objects in a database. Example: create, modify, and drop databases, tables, indexes, -:
Data Control Language (DCL) _ _ Statements control the security permissions for users and database objects. Specific user or users who belong to a database role or W Data Manipulation Language (DML) _ _ Statements used to work with data. Retrieve data (select), insert rows into a table, modify values,
and delete rows . W hat's New in SQL Server 2005? W ill be discussed in the next module and incorporation of the .NET Framework with SQL Server T-SQL and the .NET Framework Allows developers to use programming languages to write stored o ADO.NET QUICK REFERENCE - 4 SQL - Server databases. procedures oriented The uses Graphical W code, of eband Transact-SQL pages rather functions user that than interface extract (Examples) that SQLaccess statements (GUI). data from and manipulate data with object.
Example:
use master SELECT
optname,install_failures
CREATE TABLE Appointment ( AppointmentID Int , Description VarChar(50) , StartDateTime DateTime , EndDateTime DateTime ,
Data warehouses in which data is extracted from online transaction processing (OLTP) systems and summarized for decision-support analysis.
Data Manipulation Language (DML) By using DML statements, you can change data or retrieve information. DML statements include: _ _ _ _ SELECT. INSERT. UPDATE. DELETE .
FROM MSreplication_options GO
Data Definition Language (DDL) o o o Creating Objects _ _ _ Create: o o Used to create a new object Example: Table, View, Procedure, Trigger, and Function Syntax: Create <Object type> <Object Name> Syntax: Alter <Object Type> <Object Name> Syntax: Drop <Object Type> <Object Name> Altering Objects Dropping Objects
DROP: oTABLE ADO.NET QUICK REFERENCE - 5 -depends DROP Used You in intend aAppointment relationship may to to delete not drop be an able or existing if to another drop object. a object table if it contains on the data object participating you
Data Control Language (DCL) GRANT _ command gives permission set to a user or role. DENY _ command explicitly restricts a permission set. REVOKE _ object. Examples This statement grants SELECT permission to the user Product table
GRANT SELECT ON Appointment TO guest guest
unitsonorder) -- Calculates
on the
Transact-SQL Syntax Elements o o o o o o o o o _ Batch Directives Go _ send the current batch of Transact-SQL statements to SQL Server Exec _ used to execute a user-defined function, system procedure, user-defined stored procedure _ Comments _ Example This example uses an in-line comment to explain what a calculation is ADO.NET QUICK REFERENCE - 6GO doing In-line Comments _ Used to disable lines of a statement. Batch Directives Comments Identifiers Types of Data Variables Functions Operator Expressions
. /* and displays the unit price, the unit price increased by 10 percent, ADO.NET QUICK REFERENCEand the name of the product. a database table and related Metadata.
DECLARE {@local_variable
Block Comments _ Create multiple line blocks of comments. header that spans several lines nchar(11)
Example:
Example
@local_variable_name
This example shows a comment declare @str set @str='ali' SELECT @str = string FROM Table_1 where id=4 SELECT @str AS string
This code retrieves all rows of the products table */ _ Identifiers _ _ Standard Identifiers _ Delimited Identifiers Types of Data _ define the data values allowed for each column in
_ _
Variables: language elements with assigned values. You can use local variables in Transact SQL . So what is the next we must ask here a critical question, what is the difference between the Varchar and nVarchar? _ _ nVarchar _ Varchar _ for Unicode. for English where ASCII.
Syntax
- 7-
Logical operators
Aggregate Functions:Operate on the collection of values and return a single summarizing value.
SELECT AVG(id) AS Avgid FROM Table_1 GO
Scalar Functions
Rowset Functions
owner.titles)
+ +
- 8-
Bitwise
_ constant, Expressions Example: Expressions evaluate to variable, a are single a combination column data value. or scalar of They symbols value. can be and simple operators such that as a
Reserved Keywords _ _ You cannot include reserved keywords in a Transact-SQL. If an object name matches a keyword, whenever you refer to the object you must enclose it within delimiting identifiers, such as quotation marks or brackets [ ].
- 9-
Chapter 2
Data Retrieval
The SELECT Statement Filtering Rows
StandardCost, Color FROM Product
Examples
Outlines
_ _ _ _ _
Take Care!!!
Sorting Displaying the TOP Results n Rows in a Result Set Performance Considerations
General Idea
SQL queries are used to reach into the database and pull out useful information.
Clause
Explanation
W HERE ORDER BY
ADO.NET QUICK REFERENCE - 10 looks N ow, like when this: you execute this query, what happens? You get an error that
Server: Msg 209, Level 16, State 1, Line 1 Ambiguous column name 'CustomerID'. Server: Msg 209, Level 16, State 1, Line 1 Ambiguous
SELECT Customer.CustomerID , SalesOrderHeader.SalesPersonID , SalesOrderHeader.PurchaseOrderNumber FROM Customer INNER JOIN : SELECT FirstName + ' ' + LastName AS FullName FROM Contact SELECT FirstName + ' ' + LastName FullName column name 'SalesPersonID'.FROM Contact
Produces a
SELECT FirstName +
So it must be'
single
column
Column Aliasing
Examples of these three techniques
SELECT FirstName, LastName, BirthDate, DateDiff (Day, BirthDate, GetDate ())/365 As Age FROM Employee SELECT Name, ListPrice,
aliasing column
Filtering Rows
Example:
SELECT Name, ListPrice FROM Product WHERE ListPrice < 5.00
- 12 -
SELECT ProductID, Name, ListPrice FROM Product WHERE NOT SELECT ProductID,
Using OperatorsName,
SELECT FirstName, LastName, BirthDate FROM Employee SELECT FirstName, LastName, BirthDate FROM Employee SELECT Name FROM StateProvince WHERE StateProvinceCode SELECT Name, ProductNumber, ListPrice, ProductSubCategoryID FROM Product WHERE ProductSubCategoryID = 1 OR ProductSubCategoryID = 2
Examples:
ProductSubCategoryID = 1 OR ListPrice < 1000
ProductSubCategoryID = 2
- 13 -
Sorting Results
SELECT FirstName,
BirthDate DESC
Use To n to specify that you want SQL Server to return only a specific number of rows in the results
FROM Sales.SalesOrderDetail
- 14 -
Performance Considerations
_ Use positive rather than negative search conditions. Negative search conditions such as NOT BETWEEN, NOT IN, and IS NOT N ULL. May slow data retrieval because all rows are evaluated. _ Avoid using the LIKE search condition if you can write a more specific query. Data retrieval may be slower when you use the LIKE search condition. _ _ Use exact matches or ranges as search conditions when possible. Again, specific queries perform better. Data retrieval may decrease if you use the ORDER BY clause because SQL Server must determine and sort the result set before it returns the first row.
- 15 -
he ADO.NET classes are found in System.Data.dll (Root Class) and are integrated with the XML classes in System.Xml.dll.
DataSet object made up of of the
Chapter 3
hen you retrieve data, you use reader. When you work with cached locally in a relational data structure, or a dataset. W hat is ADO.NET?
represents a disconnected cache of data which is DataTables and DataRelations that represent the result command.
an object known as a data disconnected data, the data is either a data table
1.zADO.NET is the new database technology of the .NET (Dot N et) platform, and it builds on Microsoft ActiveX Data Objects (ADO). 2.zADO.NET is an integral part of the .NET Compact Framework, providing access to relational data, XML documents, and application data. 3.zADO.NET defines DataSet and DataTable objects which are optimized for moving disconnected sets of data across intranets and Internets, including through firewalls. It also includes the traditional Connection and Command objects, as well as an object called a DataReader that resembles a forward-only, read-only ADO record set. If you create a new application, your application requires some form of data access most of the time.
ADO.NET and the .NET Base Class Library The ADO.NET Object Model (Architecture) ADO.NET QUICK REFERENCE
- 17 -
The data source is the database on the Data source Connection server, but can also be many other kinds of data repositories such as an XML file.
Connected
-source 18 - specific. T hemple, information connection Connections exa Connection use to necessary are the a SqlConnection object data data to source. includes establish to make a For a
Connected
connection to a SQL database. Disconnected ADO.NET QUICK REFERENCE Connected Disconnected Disconnected
A Command object executes read and write operations on the data source. Command Command objects are data source specific and are associated with a Connection object. The DataReader represents a set of read-only, forward-only rows from a database. Use a DataReader when you DataReader need fast access and need only to read through the data from beginning to end one time. The DataReader is data source specific. A DataAdapter manages the process of communicating with the data source. Commands are associated with a DataAdapter DataAdapter. When a command is executed, the DataAdapter automatically opens and closes the connection with the data source. The DataAdapter is data source specific. The DataSet is the client-side, inmemory copy of the data. DataAdapters fill the DataSet tables, rows, and columns using data from the data source. DataSets are source neutral, meaning DataSet they can contain data from different kinds of data sources. DataSets also have multiple tables. A single DataSet can therefore be used to hold data from multiple different ADO.NET QUICK REFERENCE 19 the - DataSet sources. establish You relationships can also-use between tables.to Connected
Close connection
Golden Steps to deal with any database Connect to database Access Data
o o
Your command (insert, update, delete or delete) Determine the mechanism of retrieving data (dataset or DataReader)
- 20 -
ExecuteReader Executes commands ADO.NET QUICK REFERENCEthat return rows. For increased performance, ExecuteReader invokes commands using the Transact-SQL sp_executesql system stored procedure. Therefore, ExecuteReader might not have the effect that you want if used to execute commands such as TransactSQL SET SqlCommand class statements. ExecuteNonQuery Used to interact with database using SQL Queries or stored procedure. commands such as TransactExecutes SQL INSERT, This class cannot be inherited.For example, you can do select, insert, DELETE, UPDATE, and SET statements. modify, and delete commands on rows of data in a data base table ExecuteScalar Retrieves a single value (for example, an aggregate value) from a Important method in SqlCommanddatabase.
ADO .N ET Dataset
Represent disconnected model. Essentially this class is an in-memory database. It can contain tables made up of multiple columns of varying data types. Each table can contain multiple rows, and those rows can be related to each other through foreign keys as well complex ADO.NET QUICK REFERENCE -data 21rows -constraints. relationships assign table. new, unique, that enforce numeric parent/child identifiers to as as they are DataTables added tocan the
DataAdapter
The DataAdapter class functions very much like an electrical plug. An electrical plug connects an appliance to a power source. The DataAdapter connects a DataSet (or DataTable) to a data source. This "plug" has four prongs, one for each type of connection that can take place: InsertCommand This command is executed when an item in an associated DataTable is ready to be inserted into the data source. DeleteCommand This command is executed when an item in an associated DataTable is ready to be deleted from the data source. UpdateCommand This command is executed to commit pending changes to an item in a DataTable. SelectCommand This command is executed to populate the DataTable or DataSet with the information retrieved from the data source.
- 22 -
"connection
ensures
testConnection.Close();
- 23 -
The DbConnectionStringBuilder work like this scenario The database I am interested in connecting to . . . . . . Is on my local ADO.NET QUICK REFERENCEmachine. . . . Has the name Test. . . . Will allow me to connect using Windows authentication. . . . etc.
static void { connstrBuilder = "(local)"; "Test"; true; using new SqlConnection(conn { try {
string constituent values in order to avoid trivial programming errors as well as to make the connection string information more manageable.
testConnection.Open(); if (testConnection.State == ConnectionState.Open) { Console.WriteLine("Connection successfully opened"); Console.WriteLine("Connection string used: " + testConnection.ConnectionString); } } catch (Exception) { if (testConnection.State != ConnectionState.Open) { Console.WriteLine("Connection open failed"); Console.WriteLine("Connection string used: " testConnection.ConnectionString);
Example 1.2
- 24 -
Functionality connection string. he path of your connectionString SQL Server , Oracle , etc. In app.config write: }
<?xml version="1.0" <configuration> <connectionStrings How <add connectionString="Data
Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\AhmedRabie.mdf;Integrated _ Add Reference: System. Configuration Timeout=30;User Instance=True" Security=True;Connect providerName="System.Data.SqlClie nt "/> _ Make using to your Reference </connectionStrings>
Steps
Code:
static void Main(string[] args) { SqlConnection con N ote: = new SqlConnection(Conf igurationManager.Connection Strings["ConnStrin In scope of configuration write your connectionStrings and in g"].Co nnectionString); scope of connectionStrings write the tag that hold setting of con.Open(); if (con.State == ConnectionState.Open)
Set name to your connectionStrings to deal with it when you call the
connectionString providerName
</configuration>
- 25 -
QUICK REFERENCE
Connection.
- 26 -
2.zto use database from SQL SERVER The Microsoft universal data link (.udl) file offers a convenient, alternative method for creating and remembering complex connection strings. Steps: Create a new text file on your hard disk. Name it myfile.udl. Double-click myfile.udl to bring up the Data Link Properties Open the Provider tab and choose the Microsoft OLE DB Provider for SQL SERVER In connection tab write the name of server and then select your database file that you want to work with it. Click ok to submit your work. To view your connection string, open any notepad file and drag and drop to myfile.udl on it and it will appear like this
- 27 -
Connection Pooling
Its important to realize that the majority of the time the user might hold an open connection and not actively use it because he is busy with other parts of the application. The application could essentially time slice his expensive resourcean open connectionand pool it between ADO.NET QUICK -wish 28 -to pool multiple Using have instead, For simply instance, to connection add do you users. anything the have for following SqlClient, pooling toREFERENCE to turn use key-value with itif connection off you ADO.NET explicitly dont pair pooling to is should your really with connection you simple your the decide default because connections, string: not to settings; you usedont you it.
testConnection =
Catalog=Test;" +
SqlConnection testConnection = new SqlConnection("Data Source=(local);Initial Catalog=Test;Integrated Security=SSPI;"); long startTicks = DateTime.Now.Ticks; for (int i = 1; i <= 100; i+ +) "Integrated Security=SSPI;Pooling=false"); { testConnection.Open(); testConnection.Close(); } Example 1.3 [Demonstrating Connection long endTicks = Console.WriteLine("Time taken : " + (endTicks startTicks) + " ticks.");
Pooling in C#]
DateTime.Now.Ticks;
using System; using System.Data; using System.Data.Common; class MainClass { public static void Main(string[] args) { using (DataTable providers = DbProviderFactories.GetFactoryClasses()) { Console.WriteLine("Available Framework data providers:"); foreach (DataRow prov in providers.Rows) { Console.WriteLine("Name:{0}", prov["Name"]); testConnection.Dispose(); Console.WriteLine( "Description: {0}", prov["Description"]); Console.WriteLine( "Invariant Name:{0}", prov["InvariantName"]); } The following example will show how to get the list of ADO.NET data } }
providers registered in the machine and application configuration file Example 1.4 [Display Framework data providers]
- 29 -
using System; using System.Data; using ADO.NET QUICK REFERENCESystem.Data.SqlClient; class CommandScalar { static void Main() { The following example show how to calculate number of rows in your table SqlConnection conn = new [Do a row count using SqlCommand] ver=(local)\\SQLEXPRESS;databa SqlConnection("ser Example 1.5 se=MyDatabase;Integra ted Security=SSPI;"); string sql = @"select count(*) from employee"; SqlCommand cmd = new SqlCommand(sql, conn); Console.WriteLine("Command created and connected."); try { conn.Open(); Console.WriteLine("Number of Employees is {0}", cmd.ExecuteScalar()); } catch (SqlException ex) { Console.WriteLine(ex.ToString()); } finally { conn.Close(); Console.WriteLine("Connection Closed."); } } SqlConnection sqlCon = new SqlConnection(); sqlCon.ConnectionString = "Server=.;database=MyDataBase;uid=sa;pwd=sa "; SqlCommand sqlCmd = new SqlCommand(); sqlCmd.CommandText = "select * from studentInfo"; sqlCmd.Connection = sqlCon; SqlDataAdapter adapetr = new SqlDataAdapter(sqlCmd); DataSet daSet = new DataSet(); adapetr.Fill(daSet); sqlCon.Close(); DataTable table = daSet.Tables[0]; foreach (DataRow row in table.Rows) { Console.WriteLine(row[0]+"\t"+row[1]+"\t"+row[2]+"\n");
Example 1.6
- 30 -
that you want to display, in other hand when you make any change you need to make open because you want to enter to specific cell in table and change it but when you make retrieve you take your data as it. If you observe the previous code you will ask why I close connection before display data, the answer to this question because you fill your data from source to the memory of client so you already take copy from
"StudentInfo");
your data and you don't need to make connection continues and when you make changes in data you will make re-connection to server to commit changes. what is the difference between DataSet and DataTable? DataTable DataSet So if you have one table in your database you can use DataTable instead of DataSet. Example 1.7 [Display your Data in DataGridView]
ADO.NET QUICK REFERENCE 31 -three shape of code that do sqlCon.Close(); dataGridView1.DataSource dSet; the to fill same yor data purpose in DataAdapter you will = meet
adapter.Fill(dSet) DataTable dtable = daSet.Tables[0]; dataGridView1.DataMember = "StudentInfo"; SqlConnection sqlCon2 = new SqlConnection(); sqlCon2.ConnectionString = "Your Path here"; SqlCommand sqlCmd2 = new SqlCommand(); sqlCmd2.CommandText = "select * from StudentInfo"; sqlCmd2.Connection = sqlCon2; dataGridView1.DataSource = dSet.Tables[0]; sqlCon2.Open(); SqlDataAdapter adapter = new SqlDataAdapter(sqlCmd2); DataSet ds = new DataSet() adapter.Fill(ds); comboBox1.DataSource =ds.Tables[0]; // My dataSet comboBox1.ValueMember = "name";// dataGridView1.DataSource = dtable;This is the actual comboBox1.DataSource
=ds.Tables[0];
Example 1.8
column
name
comboBox1.ValueMember = "name";
SqlCon.Close();
SqlDataReader 32 -using Provides Server a the SqlDataReader, SqlCommand database. a way of This object, you reading class must instead a cannot call forward-only the of be directly ExecuteReader inherited. stream To of a rows constructor. method create from of a SQL
Example 1.9
SqlConnection sqlCon = new SqlConnection(); sqlCon.ConnectionString ="Your connection String"; sqlCon.Open(); ADO.NET QUICK REFERENCE SqlCommand sqlCmd = new SqlCommand(); sqlCmd.CommandText = "select * from studentInfo"; sqlCmd.Connection = sqlCon; SqlDataReader sqlReader = sqlCmd.ExecuteReader(); Console.WriteLine("ID" + "\t" + "Name" + "\t" + "Age" + "\n"); while (sqlReader.Read()) { Console.WriteLine(sqlReader[0] + "\t" + sqlReader[1] + "\t" + sqlReader[2] + "\n"); }
Example 1.10 z
SqlConnection sqlCon2 = new SqlConnection(); sqlCon2.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Documents and Settings\ahmed\My Documents\Ahmed.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"; SqlCommand sqlCmd2 = new SqlCommand(); sqlCmd2.CommandText = "select * from studentInfo"; sqlCmd2.Connection = sqlCon2; sqlCon2.Open(); SqlDataReader reader = sqlCmd2.ExecuteReader(); while (reader.Read()) sqlCon.Close(); { //or //comboBox1.Items.Add(reader[1]); comboBox1.Items.Add(reader.GetString(1)); } static void Main() { string connectionString = "you connection string"; string query = "SELECT * FROM Products"; using (SqlConnection connection =
comboBox1.Text = comboBox1.Items[0].ToString();
W hile were using an instance of SQLDataReader, were talking to it through an IDataReader interface. Talking to objects through interfaces makes our code more portablefor instance, it could more easily be converted to work with a data provider other than SQL Serverso use IDataReader unless you need additional functionality that the basic IDataReader interface doesnt support.
public class MyDetails { private int age; public int Age { get { return age; } set { age = value; } } } private string name; public string Name { get { return name; } set { name = value; } } private int id; One of the most questions asked to me, how to fill dataGridview Using public int Id { get { return id; } DataReader, if you note the behavior of DataReader you will note that set { id = when you read using DataReader you read row by row so you you make value; } }
looping to read all records if you want to display all record or any element from record , in other hand dataGridview need to take all data of your records in one package, so the solution is to make centralize store by make class that contains properties and set value for each properties when you read the value of each record and store each object from class that you create in ArrayList so the ArrayList will represent your store. Steps:-
- 34 -
while (reader.Read()) { ADO.NET QUICK REFERENCE MyDetails m = new MyDetails(); m.Id = (int)reader[0]; m.Name = reader[1].ToString(); m.Age = (int)reader[2]; sequence.Add(m); 2.zcreate ArrayList to represent your store }
SqlConnection sqlCon = null; ArrayList sequence = new ArrayList(); try { sqlCon = new SqlConnection(); sqlCon.ConnectionString = "Your Connection String"; SqlCommand cmd = new SqlCommand(); cmd.Connection = sqlCon; cmd.CommandText = "SELECT * FROM StudentInfo"; sqlCon.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { MyDetails m = new MyDetails(); m.Id = (int)reader[0]; m.Name = reader[1].ToString(); m.Age = (int)reader[2]; dataGridView1.DataSource = sequence; sequence.Add(m); } dataGridView1.DataSource = sequence; } finally { sqlCon.Close();
- 35 -
Data Binding
Data binding is the process of binding the retrieval data to control on windows forms to be displayed in a customize format. Data binding is of two types Simple Data Binding
- 36 -
public partial class ADO.NET QUICK REFERENCEForm1 : Form { ArrayList sequence = new ArrayList(); public Form1() { private void trackBar1_Scroll(object sender, EventArgs e) { this.BindingContext[ds, "StudentInfo"].Position = trackBar1.Value; } private DataSet CreateDataSet() { string customers = "SELECT * FROM StudentInfo"; DataSet ds = new DataSet(); using (SqlConnection con = new SqlConnection(@"your connection")) { SqlDataAdapter da = new SqlDataAdapter(customers, con); da.Fill(ds, "StudentInfo"); } return ds; } private void button1_Click(object sender, EventArgs e) { button1.Enabled = false; ds = CreateDataSet(); textBox1.DataBindings.Add("Text", ds, "StudentInfo.name"); textBox2.DataBindings.Add("Text", ds, "StudentInfo.job"); trackBar1.Minimum = 0; trackBar1.Maximum = this.BindingContext[ds, "StudentInfo"].Count - 1; }
- 37 -
3.zAdd 4 Buttons
private void ADO.NET QUICK REFERENCEbtnFetchData_Click(object sender, EventArgs e) { ds = FillData(); txtName.DataBindings.Add("Text", ds, "emp.Name"); txJob.DataBindings.Add("Text", ds, "emp.Job"); } private void button1_Click(object sender, EventArgs e) { this.BindingContext[ds, "emp"].Position = 0; } private void button2_Click(object sender, EventArgs e) { this.BindingContext[ds, "emp"].Position -= 1; ; } private void button3_Click(object sender, EventArgs e) { this.BindingContext[ds, "emp"].Position += 1; } private void button4_Click(object sender, EventArgs e) { this.BindingContext[ds, "emp"].Position = this.BindingContext[ds, "emp"].Count - 1; }
- 38 -
"; ";
There are to way to make Arabic column in DataGridView, the first way is so easy it depend on Change the Header Text of DataGridView as the following:
dataGridView1.Columns[0].HeaderText = " dataGridView1.Columns[1].HeaderText = " dataGridView1.Columns[2].HeaderText = " _ ____ ___ "; _
= true;
idDataGridViewTextBoxColumn.DataPropertyName = "id";
Example
private void {
idDataGridViewTextBoxColumn = new DataGridViewTextBoxColumn(); nameDataGridViewTextBoxColumn = new DataGridViewTextBoxColumn(); ageDataGridViewTextBoxColumn = new DataGridViewTextBoxColumn(); dataGridView1.Columns.AddRange(new DataGridViewTextBoxColumn[] {
Steps
3.zOk, after you add cells to dataGridView you want to make link
idDataGridViewTextBoxColumn.Name = "idDataGridViewTextBoxColumn";
= " "
____
";
ageDataGridViewTextBoxColumn.HeaderText = "
___
- 41 -
Stored procedures are SQL statements that allow you to perform a task repeatedly. You can create a procedure once and reuse it any number of times in your program
If you use a stored procedure that uses a parameter, it provides a level of protection against SQL injection attacks in a Web application. A SQL injection attack uses T-SQL code entered by a user to access unauthorized information. This can make SQL Server more vulnerable to future attack, as a hacker gathers information about the structures used in SQL Server he problem of SQL drop the table by pass drop statement in the injections see tex tbox . how I will
- 42 -
Steps
dataGridView1.DataMember = "BOOKS";
W hen you make refresh to your database you will note that your table is removed from your database.
sp_Select_All_Contacts
Contacts
Code:
- 44 -
SqlConnection con = new SqlConnection(); con.ConnectionString = @"Your Connection String Here"; SqlCommand cmd = new SqlCommand(); ADO.NET QUICK REFERENCECommandType.StoredProcedure; cmd.CommandType = cmd.CommandText = "sp_Select_By_ContactId"; cmd.Connection = con; // create input parameter SqlParameter inparm = cmd.Parameters.Add("@Contactid", SqlDbType.Int); inparm.Direction = ParameterDirection.Input; inparm.Value = 2; SqlDataAdapter ad = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); ad.Fill(ds); dataGridView1.DataSource = ds.Tables[0]; create procedure sp_Orders_By_EmployeeId2 @employeeid int, @ordercount int = 0 output as select orderid,customerid from orders where employeeid = @employeeid; select @ordercount = count(*) from orders where employeeid = @employeeid
Code:
Declare @return_value int, @ordercount int Execute @return_value=sp_Orders_By_EmployeeId2 @employeeId=2, @ordercount=@ordercount output Select @ordercount as '@ordercount'
return @ordercount
- 45 -
Parameters to Commands
As we take about the hacking, adding Injection. ADO.NET QUICK REFERENCE problem of SQL Injection and the problem of Parameters to Commands is another solution to avoid SQL
// don't ever do this! SqlCommand cmd = new SqlCommand ( "select * from Customers where city = '" + inputCity + "'";
W hen working with data, you'll often want to filter results based on some criteria. Typically, this is done by accepting input from a user and using that input to form a SQL query. For example, a sales person may need to see all orders between specific dates. Another query might be to filter customers by city. As you know, the SQL query assigned to a SqlCommand object is simply a string. So, if you want to filter a query, you could build the string dynamically, but you wouldn't want to. Here is a bad example of filtering a query .
Don't ever build a query this way! The input variable, inputCity, is typically retrieved from a TextBox control on either a Windows form or a W eb Page. Anything placed into that TextBox control will be put intoinputCity and added to your SQL string. This situation invites a hacker to replace that string with something malicious. In the worst case, you could give full control of your computer away. Instead of dynamically building a string, as shown in the bad example above, use parameters. Anything placed into a parameter will be treated as field data, not part of the SQL statement, which makes your application much more secure. Using parameterized queries is a three step process: 1.zConstruct the SqlCommand command string withas parameters. ADO.NET QUICK REFERENCE 46 - SqlCommand 2.zDeclare 3.zAssign Parameters the a SqlParameter SqlParameter property. object, object assigning to the values appropriate. object's
Example
class ParamDemo { static void Main() ADO.NET QUICK REFERENCE { // conn and reader declared outside try // block for visibility in finally block SqlConnection conn = null; SqlDataReader reader = null; string inputName = "ahmed"; try { // instantiate and open connection conn = new SqlConnection(@"your connection String here"); conn.Open(); // 1. declare command object with parameter SqlCommand cmd = new SqlCommand( "select * from StudentInfo where name = @Name", conn); // 2. define parameters used in command object SqlParameter param = new SqlParameter(); param.ParameterName = "@Name"; param.Value = inputName; // 3. add new parameter to command object cmd.Parameters.Add(param); // get data stream reader = cmd.ExecuteReader(); // write each record while (reader.Read()) { Console.WriteLine("{0}, {1}",reader["name"],reader["age"]); } } finally { // close reader if (reader != null) { reader.Close(); } // close connection if (conn != null) { conn.Close(); } } }
ADO.NET }
QUICK REFERENCE
- 47 -
using System; ADO.NET QUICK REFERENCE using System.Collections.Generic; using System.ComponentModel; using System.Data; using Example:System.Drawing; using System.Text; using This example show to make update, delete and insert using using namespace WindowsApplication9 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } SqlDataAdapter sqlDa; SqlConnection con = null; DataSet dSet; private void Form1_Load(object sender, EventArgs e) { // instantiate and open connection con = new
perimetries
System.Windows.Forms; System.Data.SqlClient;
Code:
String Here");
- 49 -
- 50 -
class Program ADO.NET QUICK REFERENCE { static void Main(string[] args) { SqlConnection con = new con.ConnectionString = SqlCommand cmd = cmd.Connection = con; StudentInfo"; cmd.CommandType = CommandType.Text; SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = cmd; DataSet dset =
DataView
con.Close(); DataTable dtable string string DataViewRowState DataViewRowState.O DataView StudentDV StudentDV.Table =
The DataView class to view only specific rows in a DataTable object = using a filterdset.Tables[0];
filterExpression = "name='ahmed'"; You can also sort the rows viewed by a DataView. sortExpression = "id DESC, name DESC"; rowStateFilter = You can add, modify, and remove rows from a DataView, and those
DataView reads fromStudentDV.RowFilter = filterExpression; StudentDV.Sort = sortExpression; StudentDV.RowStateFilter = rowStateFilter; //display data that hosted in dataView Example (DataRowView myDataViewRow in StudentDV) foreach { for (int count = 0; count <StudentDV.Table.Columns.Count-1; count++) { Console.WriteLine(myDataViewRow[count]); } Console.WriteLine("-------------------"); } }
cmd.CommandText = "Select * from
- 51 -
private void button1_Click(object sender, EventArgs e) { SqlConnection con = new ADO.NET QUICK REFERENCESqlConnection(); con.ConnectionString = @" Your connection String"; SqlCommand cmd = con.CreateCommand(); cmd.Connection = con; StudentInfo"; cmd.CommandType = CommandType.Text; SqlDataAdapter adapter = new SqlDataAdapter(); Like the previous example but show result in win control. adapter.SelectCommand = cmd; DataSet dset = new DataSet(); adapter.Fill(dset); con.Close(); DataTable dtable = dset.Tables[0]; //string filterExpression = "name='ahmed'"; string filterExpression = "name=" + "'" + textBox1.Text + "'"; string sortExpression = "id DESC, name DESC"; DataViewRowState rowStateFilter = DataViewRowState.OriginalRows; DataView StudentDV = new DataView(); StudentDV.Table = dtable; StudentDV.RowFilter = filterExpression; StudentDV.Sort = sortExpression; StudentDV.RowStateFilter = rowStateFilter;
Example
- 52 -
you set the PrimaryKey property of your DataTable and then set the
StudentDV.ApplyDefaultSort = true;
- 53 -
class Program ADO.NET QUICK REFERENCE { static void Main(string[] args) { SqlConnection con = new SqlConnection(); con.ConnectionString = @"Your Connection String"; SqlCommand cmd = con.CreateCommand(); cmd.Connection = con; StudentInfo"; cmd.CommandType = CommandType.Text; SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = cmd; DataSet dset = new DataSet(); adapter.Fill(dset); con.Close(); DataTable dtable = dset.Tables[0]; { dtable.Columns["id"]}; cmd.CommandText = "Select * from string filterExpression = "name='ahmed'"; DataViewRowState rowStateFilter = DataViewRowState.OriginalRows; DataView StudentDV = new DataView(); StudentDV.Table = dtable; StudentDV.RowFilter = filterExpression; StudentDV.ApplyDefaultSort = true; StudentDV.RowStateFilter = rowStateFilter; //display data that hosted in dataView foreach (DataRowView dtable.PrimaryKey = new DataColumn[]myDataViewRow in StudentDV) { for (int count = 0; count < StudentDV.Table.Columns.Count - 1; count++) { Console.WriteLine(myDataViewRow[count]); } Console.WriteLine("-------------------"); } } }
Example 3 :
- 54 -
example that uses the LIKE operator and the percent (%) ADO.NET QUICK REFERENCEfilter rows with a CustomerName that starts with
exp ressions in your DataView. For example, you can use AND, OR, NOT, IN, LIKE, comparison operators, arithmetic operators, wildcard
characters (* and %), and aggregate functions. StudentDRVs = StudentDV.FindRows(4); DataRowView[] foreach (DataRowView myDataRowView in StudentDRVs) { for (int count = 0; count < StudentDV.Table.Columns.Count; count++)
()
Then
Console.WriteLine(index);
()
Method ADO.NET QUICK REFERENCE - 55 - to find the DataRowView Goal: whose use ID is the 4 FindRows() method of StudentDV
DataRowView studentDRV = studentDV.AddNew(); studentDRV ["ID"] = 8; studentDRV ["Name"] = "Hossam"; studentDRV ["age"] = 25; }studentDRV.EndEdit(); studentDV Inc.:
[0].BeginEdit ();
studentDV studentDV.Delete
studentDRV DataRowView
Y ou can then modify a DataColumn in the underlying DataRow through the DataRowView. The following example sets the CompanyName DataColumn to Widgets
studentDV [0]["Name"] = "Osama"; Once you've finished making your modifications, you call the EndEdit () method to make your modifications permanent in the underlying DataTable. For example:
- 56 Removing Delete To remove () method an an Existing existing of eitherDataRowView DataRowView the DataView from or the a DataRowView. DataView, you can call the
ADO.NET QUICK REFERENCE Example to make committed to the removed row in DataTable use AcceptChanges ()
using System; using System.Data; using System.Data.SqlClient; class AddModifyAndRemoveDataRowViews { public static void DisplayDataRow( DataRow myDataRow, DataTable N otemyDataTable ) RejectChanges () method of a DataTable to undo the { Console.WriteLine("\nIn DisplayDataRow()"); foreach (DataColumn myDataColumn in myDataTable.Columns) { : AddModifyAndRemoveDataRowViews Console.WriteLine(myDataColu mn + "= " + myDataRow[myDataColumn]); } } public static void Main() { SqlConnection mySqlConnection = new SqlConnection( @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\xxxxxxxxxx.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True" ; SqlCommand mySqlCommand = mySqlConnection.CreateCommand(); mySqlCommand.CommandText = "SELECT id, name, age " + "FROM studentinfo"; SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(); mySqlDataAdapter.SelectCommand = mySqlCommand; DataSet myDataSet = new DataSet(); mySqlConnection.Open(); mySqlDataAdapter.Fill(myDataSet, "studentinfo"); mySqlConnection.Close(); DataTable studentinfoDT = myDataSet.Tables["studentinfo"]; // set up the filter expression string filterExpression = "name = 'ahmed'"; // create a DataView object named studentDV DataView studentDV = new DataView(); studentDV.Table = studentinfoDT; studentDV.RowFilter = filterExpression;
deletions
to the DataTable)
InitializeComponent();
// Connect to Database and create Controls cn = new SqlConnection(@"Your Connection String Here"); cmd = new SqlCommand("Select * from customers", cn); cmd.CommandType = CommandType.Text; da = new SqlDataAdapter(cmd); ds = new DataSet(); da.Fill(ds); RunQuery(); } public void RunQuery() { DataTable dtable = ds.Tables[0]; string filterExpression = "CustomerName='ahmed'"; { dtable.Columns["CustomerID"]}; DataView customerDv = new DataView(dtable);
QUICK REFERENCE
= customerDv;
namespace WindowsSortView { public partial class Form1 : Form { private }SqlConnection cn; private SqlCommand cmd; private SqlDataAdapter da; private DataSet ds; public Form1() { InitializeComponent(); // Connect to Database and create Controls cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\ContactsDataBase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"); cmd = new SqlCommand("Select * from customers", cn); cmd.CommandType = CommandType.Text; da = new SqlDataAdapter(cmd); ds = new DataSet(); RunQuery(); } #region Fill DataGrid with Data private void RunQuery() { try
Ex ample
Code
- 60 -
#region
- 62 -
: Form
InitializeComponent(); } #region Form1_Load private void Form1_Load(object sender, EventArgs e) { comboBox1.Items.Add("emp"); comboBox1.Items.Add("users"); } #endregion #region Method FillData return value type Dataset private DataSet FillData(string TableName) { SqlConnection con = new SqlConnection(@"Your con String"); string SQL = string.Format("select * from {0}", TableName); SqlCommand cmd = new SqlCommand(SQL, con); SqlDataAdapter ad = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); ad.Fill(ds); return ds; } #endregion #region btnFind_Click private void btnFind_Click(object sender, EventArgs e) { switch (comboBox1.Text) { case "emp": DataSet ds = FillData(comboBox1.Text); //int x = Convert.ToInt32(textBox1.Text); string FilterExpression = string.Format("name='{0}'", textBox1.Text); string SortExpression = "id desc"; DataView empDv = new DataView(); empDv.Table = ds.Tables[0]; empDv.RowFilter = FilterExpression; empDv.Sort = SortExpression; dataGridView1.DataSource = empDv; break; case "Users": DataSet ds = FillData(comboBox1.Text); //int x = Convert.ToInt32(textBox1.Text); string FilterExpression = string.Format("UserName='{0}'", textBox1.Text); string SortExpression = "Password desc"; DataView empDv = new DataView(); empDv.Table = ds.Tables[0];
Code
empDv.Sort = SortExpression; dataGridView1.DataSource = empDv; } } ADO.NET QUICK REFERENCE #endregion private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { DataSet ds = FillData(comboBox1.Text); DataView empDv = new DataView(); empDv.Table = ds.Tables[0]; dataGridView1.DataSource = empDv; }