Download presentation
Presentation is loading. Please wait.
1
2002 Prentice Hall. All rights reserved. 1 Chapter 19 – Databases, SQL, and ADO.NET Outline: 只上 19.1, 19.2, 19.3, 19.5, 19.6 19.1Introduction 19.2 Relational Database Model 19.3 Relational Database Overview: The Books Database 19.4 Structured Query Language (SQL) 19.4.1 Basic SELECT Query 19.4.2 WHERE Clause 19.4.3 ORDER BY Clause 19.4.4 Merging Data from Multiple Tables: INNER JOIN 19.4.5 Joining Data from Tables Authors, AuthorISBN, Titles and Publishers 19.4.6 INSERT Statement 19.4.7 UPDATE Statement 19.4.8 DELETE Statement 19.5 ADO.NET Object Model
2
2002 Prentice Hall. All rights reserved. 2 Outline 19.6 Programming with ADO.NET: Extracting Information from a DBMS 19.6.1 Connecting to and Querying an Access Data Source 19.6.2 Querying the Books Database 19.7 Programming with ADO.NET: Modifying a DBMS 19.8 Reading and Writing XML Files
3
2002 Prentice Hall. All rights reserved. 3 19.1 Introduction Database: –Integrated collection of data –Database management system (DBMS) Provides mechanisms for storing and organizing data in a way that is consistent with database’s format Allows storage and access to database without knowledge of internal representation –Relational Databases most popular Use Structured Query Language to perform queries (search) and manipulate data Programming languages need an interface to interact with relational databases
4
2002 Prentice Hall. All rights reserved. 4 19.2 Relational Database Model Logical representation of data: –Relationships can be considered without concern for physical structure of data Composed of tables –Rows called records –Columns called fields –Primary key: field that contains unique data Each record can be identified by at least one distinct value –New sets made from queries called result sets
5
2002 Prentice Hall. All rights reserved. 5 19.2 Relational Database Model Fig. 19.1Relational database structure of an Employee table. numbernamedepartmentsalarylocation 23603Jones4131100New Jersey 24568Kerwin4132000New Jersey 34589Larson6421800Los Angeles 35761Myers6111400Orlando 47132Neumann4139000New Jersey 78321Stephens6118500Orlando record/row field/column primary key
6
2002 Prentice Hall. All rights reserved. 6 19.3 Relational Database Overview: Books Database Rule of Entity Integrity: every record must have a unique value in its primary-key field Compound Primary key: when a record has a unique key based on a combination of two fields Foreign key: –Field for which every entry has a unique value in another table and where the field in the other table is the primary key for that table –Rule of Referential Integrity: every foreign-key field value must appear in another table’s primary-key field –One to many relationship: A foreign key can appear many times in its own table, but only once as primary key in another table
7
2002 Prentice Hall. All rights reserved. 7 19.3 Relational Database Overview: Books Database Fig. 19.2Result set formed by selecting Department and Location data from the Employee table. departmentlocation 413New Jersey 642Los Angeles 611Orlando
8
2002 Prentice Hall. All rights reserved. 8 19.3 Relational Database Overview: Books Database Fig. 19.3Authors table from Books.
9
2002 Prentice Hall. All rights reserved. 9 19.3 Relational Database Overview: Books Database Fig. 19.4Data from the Authors table of Books.
10
2002 Prentice Hall. All rights reserved. 10 19.3 Relational Database Overview: Books Database Fig. 19.5Publishers table from Books. Fig. 19.6Data from the Publishers table of Books.
11
2002 Prentice Hall. All rights reserved. 11 19.3 Relational Database Overview: Books Database Fig. 19.7AuthorISBN table from Books.
12
2002 Prentice Hall. All rights reserved. 12 19.3 Relational Database Overview: Books Database Fig. 19.8Portion of data from table AuthorISBN in database Books.
13
2002 Prentice Hall. All rights reserved. 13 19.3 Relational Database Overview: Books Database Fig. 19.9Titles table from Books.
14
2002 Prentice Hall. All rights reserved. 14 19.3 Relational Database Overview: Books Database Fig. 19.10Data from the Titles table of Books.
15
2002 Prentice Hall. All rights reserved. 15 19.3 Relational Database Overview: Books Database Fig. 19.10Data from the Titles table of Books.
16
2002 Prentice Hall. All rights reserved. 16 19.3 Relational Database Overview: Books Database Fig. 19.10Data from the Titles table of Books.
17
2002 Prentice Hall. All rights reserved. 17 19.3 Relational Database Overview: Books Database Fig. 19.10Data from the Titles table of Books.
18
2002 Prentice Hall. All rights reserved. 18 19.3 Relational Database Overview: Books Database Fig. 19.11Table relationships in Books. AuthorISBN authorID isbn Authors authorID firstName lastName Publishers publisherID publisherName Titles isbn title editionNumber copyright publisherID imageFile price 1 ¥ ¥ ¥ 1 1
19
2002 Prentice Hall. All rights reserved. 19 19.4 Structured Query Language (SQL) Used to request data (perform queries) and manipulate data
20
2002 Prentice Hall. All rights reserved. 20 19.4 Structured Query Language (SQL) Fig. 19.12SQL query keywords.
21
2002 Prentice Hall. All rights reserved. 21 19.4.1Basic Select Query Extracts information from one or more tables in a database Format: –Basic: SELECT * FROM tableName –Example: SELECT * FROM Authors –* extracts all columns –To get specific fields use a comma separated list instead of *
22
2002 Prentice Hall. All rights reserved. 22 19.4.1 Basic Select Query Fig. 19.13authorID and lastName from the Authors table.
23
2002 Prentice Hall. All rights reserved. 23 19.4.2 Where Clause Used to specify certain criteria in a query Basic form: –SELECT * FROM tableName WHERE criteria Example: –SELECT * FROM Titles WHERE copyright > 1999 Can use LIKE clause –Used for pattern matching Uses wildcards –*: zero or more characters take its place –?: exactly one character takes its place
24
2002 Prentice Hall. All rights reserved. 24 19.4.2 WHERE Clause Fig. 19.14Titles with copyrights after 1999 from table Titles.
25
2002 Prentice Hall. All rights reserved. 25 19.4.2 WHERE Clause Fig. 19.15Authors whose last names start with D from the Authors table. Fig. 19.16The authors from the Authors table whose last names contain i as their second letter.
26
2002 Prentice Hall. All rights reserved. 26 19.4.3 ORDER BY Clause Used to arrange results of a query –Can be ascending or descending order Uses ASC and DESC respectively Example: –SELECT authorID FROM Authors ORDER BY authorID ASC Can be used to sort by multiple fields
27
2002 Prentice Hall. All rights reserved. 27 19.4.3 ORDER BY Clause Fig. 19.17Authors from table Authors in ascending order by lastName.
28
2002 Prentice Hall. All rights reserved. 28 19.4.3 ORDER BY Clause Fig. 19.18Authors from table Authors in descending order by lastName.
29
2002 Prentice Hall. All rights reserved. 29 19.4.3 ORDER BY Clause Fig. 19.19Authors from table Authors in ascending order by lastName and by firstName.
30
2002 Prentice Hall. All rights reserved. 30 19.4.3 ORDER BY Clause Fig. 19.20Books from table Titles whose titles end with How to Program in ascending order by title.
31
2002 Prentice Hall. All rights reserved. 31 19.4.4 Merging Data from Multiple Tables: INNER JOIN INNER JOIN –Merges records from multiple tables into a single record –Tests for matching values in a common field –General Form: SELECT * FROM table1 INNER JOIN table2 ON table1.fieldName=table2.fieldName –Example: SELECT firstName, isbn FROM Authors INNER JOIN AuthorISBN ON Authors.authorID= AuthorISBN.authorID Fully-qualified names use the table name and dot operator followed by the field name
32
2002 Prentice Hall. All rights reserved. 32 19.4.4 Merging Data from Multiple Tables: INNER JOIN Fig. 19.21Portion of the authors and the ISBN numbers for the books they have written in ascending order by lastName and firstName.
33
2002 Prentice Hall. All rights reserved. 33 19.4.5 Joining Data from Tables Authors, AuthorISBN, Titles and Publishers Tables produced by INNER JOIN can be used as arguments for another INNER JOIN
34
2002 Prentice Hall. All rights reserved. 34 19.4.5 Joining Data from Tables Authors, AuthorISBN, Titles and Publishers Fig. 19.22 TitleAuthor query of Books database. Join Publishers and Titles tables if the publisherID matches Join Authors and AuthorISBN if authorID matches Join two created tables if titlesISBN matches authorsISBN Sort new table by title
35
2002 Prentice Hall. All rights reserved. 35 19.4.5 Joining Data from Tables Authors, AuthorISBN, Titles and Publishers Fig. 19.23Portion of the result set produced by the query in Fig. 19.22.
36
2002 Prentice Hall. All rights reserved. 36 19.4.5 Joining Data from Tables Authors, AuthorISBN, Titles and Publishers Fig. 19.23Portion of the result set produced by the query in Fig. 19.22.
37
2002 Prentice Hall. All rights reserved. 37 19.4.6 Insert Statement Inserts a new record into a table Form: INSERT INTO tableName(fieldName1) VALUES (value1) Values must match field names in order and type
38
2002 Prentice Hall. All rights reserved. 38 19.4.6 INSERT Statement Fig. 19.24Table Authors after an INSERT INTO operation to add a record.
39
2002 Prentice Hall. All rights reserved. 39 19.4.7 UPDATE Statement Modifies data in a table Form: UPDATE tableName SET fieldName1 = value1 WHERE criteria
40
2002 Prentice Hall. All rights reserved. 40 19.4.7 UPDATE Statement Fig. 19.25Table Authors after an UPDATE operation to change a record.
41
2002 Prentice Hall. All rights reserved. 41 19.4.8 DELETE Statement Removes data from a table Form: DELETE FROM tableName WHERE criteria
42
2002 Prentice Hall. All rights reserved. 42 19.4.8 DELETE Statement Fig. 19.26Table Authors after a DELETE operation to remove a record.
43
2002 Prentice Hall. All rights reserved. 43 19.5 ADO.NET and Object Model Provides an API for accessing database systems programmatically Namespaces: –System.Data System.Data.DataSet: DataTables and their relationships represent a cache of data. Store data from source in local memory –System.Data.OleDb: classes to work with any datasource OleDbConnection: a connect to a datasource OleDbDataAdapter: connect to a datasource through an instance of OleDbConnection and can populate DataSet with data from a datasource OleDbCommand: represent a SQL command to be executed on a datasource. Do not cache data in local memory –System.Data.SqlClient: classes that are optimized to work with MS SQL Server 2000
44
2002 Prentice Hall. All rights reserved. 44 19.6 Programming with ADO.NET: Extracting Information from a DBMS Examples that demonstrate how to connect to a database, query the database and display the results of the query 1. 工具 -> 連接資料庫 –MicroSoft Jet 4.0 OLE DB Provider – 選擇 Access 資料庫 2. 在 “ 伺服器總管 ” 拖曳 資料庫 至 表單 以 產生 OldDbConnection1 3. 在 “ 資料 ” 拖曳 OldDbDataAdapter 至表單, 在精靈的問項保留 預設值, 按 “ 查詢產生器 ”, 選擇 Authors 表格, 在 ‘*’ 左邊打 4. 在 “ 資料 ” 拖曳 DataSet, 選擇 “ 不具型別資料集 ” 5. 在程式碼第 12 行 ( initializeComponent ) 之後加上 OleDbDataAdapter1.Fill(DataSet1, "Authors") DataGrid1.SetDataBinding(DataSet1, "Authors")
45
2002 Prentice Hall. All rights reserved. 45 19.6.1 Connecting to and Querying an Access Data Source Retrieves data and stores it in a DataGrid
46
2002 Prentice Hall. All rights reserved. Outline 46 DisplayTable.vb 1 ' Fig. 19.27: DisplayTable.vb 2 ' Displaying data from a database table. 3 4 Public Class FrmTableDisplay 5 Inherits System.Windows.Forms.Form 6 7 #Region " Windows Form Designer generated code " 8 9 Public Sub New() 10 MyBase.New() 11 12 ' This call is required by the Windows Form Designer. 13 InitializeComponent() 14 15 ' Add any initialization after the 16 ' InitializeComponent() call 17 18 ' fill DataSet11 with data 19 OleDbDataAdapter1.Fill(DataSet1, "Authors") 20 21 ' bind data in Users table in dataSet11 to dgdAuthors 22 dgdAuthors.SetDataBinding(DataSet1, "Authors") 23 End Sub ' New 24 25 ' Form overrides dispose to clean up the component list. 26 Protected Overloads Overrides Sub Dispose( _ 27 ByVal disposing As Boolean) 28 29 If disposing Then 30 If Not (components Is Nothing) Then 31 components.Dispose() 32 End If 33 End If 34 MyBase.Dispose(disposing) 35 End Sub ' Dispose Constructor to populate dataSet1Call method fill to retrieve data from database associated with oleDbConnection Bind DataGrid to data source
47
2002 Prentice Hall. All rights reserved. Outline 47 DisplayTable.vb 36 37 Friend WithEvents dgdAuthors As System.Windows.Forms.DataGrid 38 Friend WithEvents OleDbSelectCommand1 As _ 39 System.Data.OleDb.OleDbCommand 40 41 Friend WithEvents OleDbInsertCommand1 As _ 42 System.Data.OleDb.OleDbCommand 43 44 Friend WithEvents OleDbUpdateCommand1 As _ 45 System.Data.OleDb.OleDbCommand 46 47 Friend WithEvents OleDbDeleteCommand1 As _ 48 System.Data.OleDb.OleDbCommand 49 50 Friend WithEvents OleDbConnection1 As _ 51 System.Data.OleDb.OleDbConnection 52 53 Friend WithEvents OleDbDataAdapter1 As _ 54 System.Data.OleDb.OleDbDataAdapter 55 56 Friend WithEvents DataSet1 As System.Data.DataSet 57 58 ' Required by the Windows Form Designer 59 Private components As System.ComponentModel.Container 60 61 ' NOTE: The following procedure is required by the 62 ' Windows Form Designer 63 ' It can be modified using the Windows Form Designer. 64 ' Do not modify it using the code editor. 65 _ 66 Private Sub InitializeComponent() 67 68 Me.dgdAuthors = New System.Windows.Forms.DataGrid() 69 Me.OleDbSelectCommand1 = _ 70 New System.Data.OleDb.OleDbCommand()
48
2002 Prentice Hall. All rights reserved. Outline 48 DisplayTable.vb 71 72 Me.OleDbInsertCommand1 = _ 73 New System.Data.OleDb.OleDbCommand() 74 75 Me.OleDbUpdateCommand1 = _ 76 New System.Data.OleDb.OleDbCommand() 77 78 Me.OleDbDeleteCommand1 = _ 79 New System.Data.OleDb.OleDbCommand() 80 81 Me.OleDbConnection1 = _ 82 New System.Data.OleDb.OleDbConnection() 83 84 Me.OleDbDataAdapter1 = _ 85 New System.Data.OleDb.OleDbDataAdapter() 86 87 Me.DataSet1 = New System.Data.DataSet() 88 CType(Me.dgdAuthors, _ 89 System.ComponentModel.ISupportInitialize).BeginInit() 90 91 CType(Me.DataSet1, _ 92 System.ComponentModel.ISupportInitialize).BeginInit() 93 94 Me.SuspendLayout() 95 96 ' 97 ' dgdAuthors 98 ' 99 Me.dgdAuthors.DataMember = "" 100 Me.dgdAuthors.Location = New System.Drawing.Point(8, 8) 101 Me.dgdAuthors.Name = "dgdAuthors" 102 Me.dgdAuthors.Size = New System.Drawing.Size(304, 256) 103 Me.dgdAuthors.TabIndex = 0 104
49
2002 Prentice Hall. All rights reserved. Outline 49 DisplayTable.vb 105 ' 106 ' OleDbSelectCommand1 107 ' 108 Me.OleDbSelectCommand1.CommandText = _ 109 "SELECT authorID, firstName, lastName FROM Authors" 110 111 Me.OleDbSelectCommand1.Connection = Me.OleDbConnection1 112 113 ' 114 ' OleDbInsertCommand1 115 ' 116 Me.OleDbInsertCommand1.CommandText = _ 117 "INSERT INTO Authors(authorID, firstName, lastName)" & _ 118 "VALUES (?, ?, ?)" 119 120 Me.OleDbInsertCommand1.Connection = _ 121 Me.OleDbConnection1 122 123 Me.OleDbInsertCommand1.Parameters.Add _ 124 (New System.Data.OleDb.OleDbParameter("authorID", _ 125 System.Data.OleDb.OleDbType.Numeric, 0, _ 126 System.Data.ParameterDirection.Input, False, _ 127 CType(10, Byte), CType(0, Byte), "authorID", _ 128 System.Data.DataRowVersion.Current, Nothing)) 129 130 Me.OleDbInsertCommand1.Parameters.Add _ 131 (New System.Data.OleDb.OleDbParameter("firstName", _ 132 System.Data.OleDb.OleDbType.Char, 50, _ 133 System.Data.ParameterDirection.Input, False, _ 134 CType(0, Byte), CType(0, Byte), "firstName", _ 135 System.Data.DataRowVersion.Current, Nothing)) 136
50
2002 Prentice Hall. All rights reserved. Outline 50 DisplayTable.vb 137 Me.OleDbInsertCommand1.Parameters.Add _ 138 (New System.Data.OleDb.OleDbParameter("lastName", _ 139 System.Data.OleDb.OleDbType.Char, 50, _ 140 System.Data.ParameterDirection.Input, False, _ 141 CType(0, Byte), CType(0, Byte), "lastName", _ 142 System.Data.DataRowVersion.Current, Nothing)) 143 144 ' 145 ' OleDbUpdateCommand1 146 ' 147 Me.OleDbUpdateCommand1.CommandText = _ 148 "UPDATE Authors SET authorID = ?, firstName = ?, " & _ 149 "lastName = ? WHERE (authorID = ?)" & _ 150 " AND (firstName = ?) AND (lastName = ?)" 151 152 Me.OleDbUpdateCommand1.Connection = Me.OleDbConnection1 153 Me.OleDbUpdateCommand1.Parameters.Add _ 154 (New System.Data.OleDb.OleDbParameter("authorID", _ 155 System.Data.OleDb.OleDbType.Numeric, 0, _ 156 System.Data.ParameterDirection.Input, False, _ 157 CType(10, Byte), CType(0, Byte), "authorID", _ 158 System.Data.DataRowVersion.Current, Nothing)) 159 160 Me.OleDbUpdateCommand1.Parameters.Add _ 161 (New System.Data.OleDb.OleDbParameter("firstName", _ 162 System.Data.OleDb.OleDbType.Char, 50, _ 163 System.Data.ParameterDirection.Input, False, _ 164 CType(0, Byte), CType(0, Byte), "firstName", _ 165 System.Data.DataRowVersion.Current, Nothing)) 166 Set connection property for oleDbUpdateCommand1 Set CommandText for oleDbUpdateCommand1
51
2002 Prentice Hall. All rights reserved. Outline 51 DisplayTable.vb 167 Me.OleDbUpdateCommand1.Parameters.Add _ 168 (New System.Data.OleDb.OleDbParameter("lastName", _ 169 System.Data.OleDb.OleDbType.Char, 50, _ 170 System.Data.ParameterDirection.Input, False, _ 171 CType(0, Byte), CType(0, Byte), "lastName", _ 172 System.Data.DataRowVersion.Current, Nothing)) 173 174 Me.OleDbUpdateCommand1.Parameters.Add _ 175 (New System.Data.OleDb.OleDbParameter _ 176 ("Original_authorID", _ 177 System.Data.OleDb.OleDbType.Numeric, 0, _ 178 System.Data.ParameterDirection.Input, False, _ 179 CType(10, Byte), CType(0, Byte), "authorID", _ 180 System.Data.DataRowVersion.Original, Nothing)) 181 182 Me.OleDbUpdateCommand1.Parameters.Add _ 183 (New System.Data.OleDb.OleDbParameter _ 184 ("Original_firstName", _ 185 System.Data.OleDb.OleDbType.Char, 50, _ 186 System.Data.ParameterDirection.Input, False, _ 187 CType(0, Byte), CType(0, Byte), "firstName", _ 188 System.Data.DataRowVersion.Original, Nothing)) 189 190 Me.OleDbUpdateCommand1.Parameters.Add _ 191 (New System.Data.OleDb.OleDbParameter _ 192 ("Original_lastName", _ 193 System.Data.OleDb.OleDbType.Char, 50, _ 194 System.Data.ParameterDirection.Input, False, _ 195 CType(0, Byte), CType(0, Byte), "lastName", _ 196 System.Data.DataRowVersion.Original, Nothing)) 197
52
2002 Prentice Hall. All rights reserved. Outline 52 DisplayTable.vb 198 ' 199 ' OleDbDeleteCommand1 200 ' 201 Me.OleDbDeleteCommand1.CommandText = _ 202 "DELETE FROM Authors WHERE (authorID = ?) AND " & _ 203 "(firstName = ?) AND (lastName = ?)" 204 205 Me.OleDbDeleteCommand1.Connection = Me.OleDbConnection1 206 Me.OleDbDeleteCommand1.Parameters.Add _ 207 (New System.Data.OleDb.OleDbParameter("authorID", _ 208 System.Data.OleDb.OleDbType.Numeric, 0, _ 209 System.Data.ParameterDirection.Input, False, _ 210 CType(10, Byte), CType(0, Byte), "authorID", _ 211 System.Data.DataRowVersion.Original, Nothing)) 212 213 Me.OleDbDeleteCommand1.Parameters.Add _ 214 (New System.Data.OleDb.OleDbParameter("firstName", _ 215 System.Data.OleDb.OleDbType.Char, 50, _ 216 System.Data.ParameterDirection.Input, False, _ 217 CType(0, Byte), CType(0, Byte), "firstName", _ 218 System.Data.DataRowVersion.Original, Nothing)) 219 220 Me.OleDbDeleteCommand1.Parameters.Add _ 221 (New System.Data.OleDb.OleDbParameter("lastName", _ 222 System.Data.OleDb.OleDbType.Char, 50, _ 223 System.Data.ParameterDirection.Input, False, _ 224 CType(0, Byte), CType(0, Byte), "lastName", _ 225 System.Data.DataRowVersion.Original, Nothing)) 226
53
2002 Prentice Hall. All rights reserved. Outline 53 DisplayTable.vb 227 ' 228 'OleDbConnection1 229 ' 230 Me.OleDbConnection1.ConnectionString = _ 231 "Provider=Microsoft.Jet.OLEDB.4.0;Password="""";" & _ 232 "User ID=Admin;Data Source=C:\Documen" & _ 233 "ts and Settings\thiago\Desktop\vbhtp2e\examples\" & _ 234 "Ch19\Fig19_27\Books.mdb;Mode=Sha" & _ 235 "re Deny None;Extended Properties="""";" & _ 236 "Jet OLEDB:System database="""";Jet OLEDB:Regis" & _ 237 "try Path="""";Jet OLEDB:Database Password="""";" & _ 238 "Jet OLEDB:Engine Type=5;Jet OLEDB:Dat" & _ 239 "abase Locking Mode=1;Jet OLEDB:Global Partial " & _ 240 "Bulk Ops=2;Jet OLEDB:Global Bulk T" & _ 241 "ransactions=1;Jet OLEDB:New Database " & _ 242 "Password="""";Jet OLEDB:Create System Databas" & _ 243 "e=False;Jet OLEDB:Encrypt Database=False;" & _ 244 "Jet OLEDB:Don't Copy Locale on Compact=" & _ 245 "False;Jet OLEDB:Compact Without Replica " & _ 246 "Repair=False;Jet OLEDB:SFP=False" 247 248 ' 249 ' OleDbDataAdapter1 250 ' 251 Me.OleDbDataAdapter1.DeleteCommand = _ 252 Me.OleDbDeleteCommand1 253 254 Me.OleDbDataAdapter1.InsertCommand = _ 255 Me.OleDbInsertCommand1 256 257 Me.OleDbDataAdapter1.SelectCommand = _ 258 Me.OleDbSelectCommand1 259 Initialize oleDbConnection, and specify path to database Specify how oleDbDataAdapter deletes data Specify how oleDbDataAdapter inserts data Specify how oleDbDataAdapter selects data
54
2002 Prentice Hall. All rights reserved. Outline 54 DisplayTable.vb 260 Me.OleDbDataAdapter1.TableMappings.AddRange _ 261 (New System.Data.Common.DataTableMapping() _ 262 {New System.Data.Common.DataTableMapping("Table", _ 263 "Authors", New System.Data.Common.DataColumnMapping() _ 264 {New System.Data.Common.DataColumnMapping("authorID", _ 265 "authorID"), New System.Data.Common.DataColumnMapping _ 266 ("firstName", "firstName"), _ 267 New System.Data.Common.DataColumnMapping("lastName", _ 268 "lastName")})}) 269 270 Me.OleDbDataAdapter1.UpdateCommand = _ 271 Me.OleDbUpdateCommand1 272 273 ' 274 ' DataSet1 275 ' 276 Me.DataSet1.DataSetName = "NewDataSet" 277 Me.DataSet1.Locale = _ 278 New System.Globalization.CultureInfo("en-US") 279 280 ' 281 ' FrmTableDisplay 282 ' 283 Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) 284 Me.ClientSize = New System.Drawing.Size(320, 273) 285 Me.Controls.AddRange(New System.Windows.Forms.Control() _ 286 {Me.dgdAuthors}) 287 288 Me.Name = "FrmTableDisplay" 289 Me.Text = "Table Display" 290 CType(Me.dgdAuthors, System.ComponentModel. _ 291 ISupportInitialize).EndInit() 292 293 CType(Me.DataSet1, System.ComponentModel. _ 294 ISupportInitialize).EndInit() Specify how oleDbDataAdapter updates data
55
2002 Prentice Hall. All rights reserved. Outline 55 DisplayTable.vb 295 296 Me.ResumeLayout(False) 297 298 End Sub ' InitializeComponent 299 300 #End Region 301 302 End Class ' FrmTableDisplay
56
2002 Prentice Hall. All rights reserved. 56 19.6.2 Querying the Books Database Use SELECT statements on database and display results
57
2002 Prentice Hall. All rights reserved. Outline 57 DisplayQueryResu lts.vb 1 ' Fig. 19.28: DisplayQueryResults.vb 2 ' Displays the contents of the authors database. 3 4 Public Class FrmDisplayQueryResult 5 Inherits System.Windows.Forms.Form 6 7 Friend WithEvents txtQuery As System.Windows.Forms.TextBox 8 Friend WithEvents cmdSubmit As System.Windows.Forms.Button 9 Friend WithEvents dgdResults As System.Windows.Forms.DataGrid 10 Friend WithEvents BooksConnection As _ 11 System.Data.OleDb.OleDbConnection 12 13 Friend WithEvents BooksDataAdapter As _ 14 System.Data.OleDb.OleDbDataAdapter 15 16 Friend WithEvents BooksDataSet As System.Data.DataSet 17 18 ' Visual Studio.NET generated code 19 20 ' perform SQL query on data 21 Private Sub cmdSubmit_Click(ByVal sender As System.Object, _ 22 ByVal e As System.EventArgs) Handles cmdSubmit.Click 23 24 Try 25 26 ' set the text of the SQL query to what the user typed 27 ' in 28 BooksDataAdapter.SelectCommand.CommandText = _ 29 txtQuery.Text 30 31 ' clear the DataSet from the previous operation 32 BooksDataSet.Clear() 33 Form FrmDisplayQueryResult contains TextBox txtQuery, in which users input SELECT statements After entering a query, the user clicks Button cmdSubmit, labeled Submit Query, to view the results of the query
58
2002 Prentice Hall. All rights reserved. Outline 58 DisplayQueryResu lts.vb Program Output 34 ' Fill the data set with the information that results 35 ' from the SQL query 36 BooksDataAdapter.Fill(BooksDataSet, "Authors") 37 38 ' Bind the DataGrid to the contents of the DatSet 39 dgdResults.SetDataBinding(BooksDataSet, "Authors") 40 41 ' display database connection verbose message 42 Catch exception As System.Data.OleDb.OleDbException 43 MessageBox.Show("Invalid Query") 44 End Try 45 46 End Sub ' cmdSubmit_Click 47 48 End Class ' FrmDisplayQueryResults
59
2002 Prentice Hall. All rights reserved. 59 19.7 Programming with ADO.NET: Modifying a DBMS Example implements an address book –User can insert, locate and update records
60
2002 Prentice Hall. All rights reserved. Outline 60 AddressBook.vb 1 ' Fig. 19.29: AddressBook.vb 2 ' Using SQL statements to manipulate a database. 3 4 Imports System.Windows.Forms 5 6 Public Class FrmAddressBook 7 Inherits Form 8 9 ' top set of command buttons 10 Friend WithEvents cmdFind As Button 11 Friend WithEvents cmdAdd As Button 12 Friend WithEvents cmdUpdate As Button 13 Friend WithEvents cmdClear As Button 14 Friend WithEvents cmdHelp As Button 15 16 ' textbox identifier labels 17 Friend WithEvents lblId As Label 18 Friend WithEvents lblFirst As Label 19 Friend WithEvents lblLast As Label 20 Friend WithEvents lblAddress As Label 21 Friend WithEvents lblCity As Label 22 Friend WithEvents lblState As Label 23 Friend WithEvents lblZip As Label 24 Friend WithEvents lblCountry As Label 25 Friend WithEvents lblEmail As Label 26 Friend WithEvents lblPhone As Label 27 Friend WithEvents lblFax As Label 28 29 ' input textboxes 30 Friend WithEvents txtId As TextBox 31 Friend WithEvents txtFirst As TextBox 32 Friend WithEvents txtLast As TextBox 33 Friend WithEvents txtAddress As TextBox 34 Friend WithEvents txtCity As TextBox 35 Friend WithEvents txtState As TextBox
61
2002 Prentice Hall. All rights reserved. Outline 61 AddressBook.vb 36 Friend WithEvents txtZip As TextBox 37 Friend WithEvents txtCountry As TextBox 38 Friend WithEvents txtEmail As TextBox 39 Friend WithEvents txtPhone As TextBox 40 Friend WithEvents txtFax As TextBox 41 42 ' query status display textbox 43 Friend WithEvents txtStatus As TextBox 44 45 ' database connection 46 Friend WithEvents AddressBookConnection As _ 47 System.Data.OleDb.OleDbConnection 48 49 ' database adapter 50 Friend WithEvents AddressBookDataAdapter As _ 51 System.Data.OleDb.OleDbDataAdapter 52 53 ' query dataset 54 Friend WithEvents AddressBookDataSet As System.Data.DataSet 55 56 ' constructor 57 Public Sub New() 58 MyBase.New() 59 60 ' This call is required by the Windows Form Designer. 61 InitializeComponent() 62 63 ' Add any initialization after the InitializeComponent call 64 65 ' open connection 66 AddressBookConnection.Open() 67 End Sub ' New 68 69 ' Visual Studio.NET generated code 70
62
2002 Prentice Hall. All rights reserved. Outline 62 AddressBook.vb 71 ' finds record in database 72 Private Sub cmdFind_Click(ByVal sender As System.Object, _ 73 ByVal e As System.EventArgs) Handles cmdFind.Click 74 75 Try 76 77 ' ensure user input last name 78 If txtLast.Text <> "" Then 79 80 ' clear DataSet from last operation 81 AddressBookDataSet.Clear() 82 83 ' create SQL query to find contact 84 ' with specified last name 85 AddressBookDataAdapter.SelectCommand.CommandText = _ 86 "SELECT * FROM addresses WHERE " & _ 87 "lastname = '" & txtLast.Text & "' " 88 89 ' fill AddressBookDataSet with the rows resulting 90 ' from the query 91 AddressBookDataAdapter.Fill(AddressBookDataSet) 92 93 ' display information 94 Display(AddressBookDataSet) 95 txtStatus.Text &= vbCrLf & "Query Successful " & _ 96 vbCrLf 97 98 ' prompt user for last name 99 Else 100 txtLast.Text = _ 101 "Enter last name here then press Find" 102 End If 103 104 ' display verbose information with database exception 105 Catch oleDbExceptionParameter As _ Method Clear of class DataSet is invoked to empty the DataSet of any prior data The TextBox es are updated with a call to method Display Event handler cmdFind_Click performs the SELECT query on the database for the record associated with the String entered in txtLast
63
2002 Prentice Hall. All rights reserved. Outline 63 AddressBook.vb 106 System.Data.OleDb.OleDbException 107 108 Console.WriteLine(oleDbExceptionParameter.StackTrace) 109 txtStatus.Text &= oleDbExceptionParameter.ToString 110 111 ' display message box when invalid operation 112 Catch invalidOperationExceptionParameter As _ 113 InvalidOperationException 114 115 MessageBox.Show( _ 116 invalidOperationExceptionParameter.Message) 117 End Try 118 119 End Sub ' cmdFind_Click 120 121 ' adds record to database 122 Private Sub cmdAdd_Click(ByVal sender As System.Object, _ 123 ByVal e As System.EventArgs) Handles cmdAdd.Click 124 125 Try 126 127 ' ensure first and last name input 128 If (txtLast.Text <> "" AndAlso txtFirst.Text <> "") Then 129 130 ' create the SQL query to insert a row 131 AddressBookDataAdapter.InsertCommand.CommandText = _ 132 "INSERT INTO addresses(firstname, " & _ 133 "lastname, address, city, " & _ 134 "stateorprovince, postalcode, country, " & _ 135 "emailaddress, homephone, faxnumber) " & _ 136 "VALUES('" & txtFirst.Text & "', " & _ 137 "'" & txtLast.Text & "', " & _ 138 "'" & txtAddress.Text & "', " & _ 139 "'" & txtCity.Text & "', " & _ 140 "'" & txtState.Text & "', " & _ Method cmdAdd_Click performs INSERT and UPDATE operations
64
2002 Prentice Hall. All rights reserved. Outline 64 AddressBook.vb 141 "'" & txtZip.Text & "', " & _ 142 "'" & txtCountry.Text & "', " & _ 143 "'" & txtEmail.Text & "', " & _ 144 "'" & txtPhone.Text & "', " & _ 145 "'" & txtFax.Text & "')" 146 147 ' notify the user the query is being sent 148 txtStatus.Text &= vbCrLf & "Sending query: " & _ 149 AddressBookDataAdapter.InsertCommand. _ 150 CommandText & vbCrLf 151 152 ' send query 153 AddressBookDataAdapter.InsertCommand. _ 154 ExecuteNonQuery() 155 156 txtStatus.Text &= vbCrLf & "Query successful" 157 158 ' prompt user to input first and last name 159 Else 160 txtStatus.Text &= vbCrLf & _ 161 "Enter at least first and last name then " & _ 162 "press Add" & vbCrLf 163 End If 164 165 ' display verbose information when database exception 166 Catch oleDbExceptionParameter As _ 167 System.Data.OleDb.OleDbException 168 169 Console.WriteLine(oleDbExceptionParameter.StackTrace) 170 txtStatus.Text &= oleDbExceptionParameter.ToString 171 End Try 172 173 End Sub ' cmdAdd_Click 174 175 ' updates entry in database
65
2002 Prentice Hall. All rights reserved. Outline 65 AddressBook.vb 176 Private Sub cmdUpdate_Click(ByVal sender As System.Object, _ 177 ByVal e As System.EventArgs) Handles cmdUpdate.Click 178 179 Try 180 181 ' make sure user has already found 182 ' record to update 183 If txtId.Text <> "" Then 184 185 ' set SQL query to update all fields in 186 ' table where id number matches id in 187 ' idTextBox 188 AddressBookDataAdapter.UpdateCommand.CommandText = _ 189 "UPDATE addresses SET firstname=" & _ 190 "'" & txtFirst.Text & "', " & _ 191 "lastname = '" & txtLast.Text & "', " & _ 192 "address='" & txtAddress.Text & "', " & _ 193 "city='" & txtCity.Text & "', " & _ 194 "stateorprovince= " & _ 195 "'" & txtState.Text & "', " & _ 196 "postalcode='" & txtZip.Text & "', " & _ 197 "country='" & txtCountry.Text & "', " & _ 198 "emailaddress='" & txtEmail.Text & "', " & _ 199 "homephone='" & txtPhone.Text & "', " & _ 200 "faxnumber='" & txtFax.Text & "' " & _ 201 "WHERE id=" & txtId.Text & " ; " 202 203 ' notify user that query is being sent 204 txtStatus.Text &= vbCrLf & "Sending query: " & _ 205 AddressBookDataAdapter.UpdateCommand. _ 206 CommandText & vbCrLf 207 208 ' execute query 209 AddressBookDataAdapter.UpdateCommand. _ 210 ExecuteNonQuery()
66
2002 Prentice Hall. All rights reserved. Outline 66 AddressBook.vb 211 212 txtStatus.Text &= vbCrLf & "Query Successful" & _ 213 vbCrLf 214 215 ' prompt user to input existing record 216 Else 217 txtStatus.Text &= vbCrLf & _ 218 "You may only update an existing record. " & _ 219 "Use Find to locate the record, then " & _ 220 "modify the information and press Update." & _ 221 vbCrLf 222 End If 223 224 ' display verbose information when database exception 225 Catch oleDbExceptionParameter As _ 226 System.Data.OleDb.OleDbException 227 228 Console.WriteLine(oleDbExceptionParameter.StackTrace) 229 txtStatus.Text &= oleDbExceptionParameter.ToString 230 End Try 231 232 End Sub ' cmdUpdate_Click 233 234 ' clears all information in textboxes 235 Private Sub cmdClear_Click(ByVal sender As System.Object, _ 236 ByVal e As System.EventArgs) Handles cmdClear.Click 237 238 txtId.Clear() 239 ClearTextBoxes() 240 End Sub ' cmdClear_Click 241 242 ' displays information on application use 243 Private Sub cmdHelp_Click(ByVal sender As System.Object, _ 244 ByVal e As System.EventArgs) Handles cmdHelp.Click 245
67
2002 Prentice Hall. All rights reserved. Outline 67 AddressBook.vb 246 txtStatus.AppendText(vbCrLf & _ 247 "Click Find to locate a record" & vbCrLf & _ 248 "Click Add to insert a new record." & vbCrLf & _ 249 "Click Update to update the information in a " & _ 250 "record " & vbCrLf & "Click Clear to empty the " & _ 251 "textboxes") 252 End Sub ' cmdHelp_Click 253 254 ' displays data in dataset 255 Private Sub Display(ByVal dataset As DataSet) 256 257 Try 258 259 ' get first DataTable - there will be one 260 Dim dataTable As DataTable = dataset.Tables(0) 261 262 ' ensure dataTable not empty 263 If dataTable.Rows.Count <> 0 Then 264 Dim recordNumber As Integer = _ 265 Convert.ToInt32(dataTable.Rows(0)(0)) 266 267 txtId.Text = recordNumber.ToString 268 txtFirst.Text = _ 269 Convert.ToString(dataTable.Rows(0)(1)) 270 271 txtLast.Text = _ 272 Convert.ToString(dataTable.Rows(0)(2)) 273 274 txtAddress.Text = _ 275 Convert.ToString(dataTable.Rows(0)(3)) 276 277 txtCity.Text = _ 278 Convert.ToString(dataTable.Rows(0)(4)) 279 280 txtState.Text = _ Retrieve the remaining fields of data from the DataTable to populate the user interface Retrieves the field with index 0, 0 and stores the value in variable recordNumber Checks whether the query returned any rows Method Display updates the user interface with data from the newly retrieved address book record
68
2002 Prentice Hall. All rights reserved. Outline 68 AddressBook.vb 281 Convert.ToString(dataTable.Rows(0)(5)) 282 283 txtZip.Text = _ 284 Convert.ToString(dataTable.Rows(0)(6)) 285 286 txtCountry.Text = _ 287 Convert.ToString(dataTable.Rows(0)(7)) 288 289 txtEmail.Text = _ 290 Convert.ToString(dataTable.Rows(0)(8)) 291 292 txtPhone.Text = _ 293 Convert.ToString(dataTable.Rows(0)(9)) 294 295 txtFax.Text = _ 296 Convert.ToString(dataTable.Rows(0)(10)) 297 298 ' display not-found message 299 Else 300 txtStatus.Text &= vbCrLf & "No record found“ & vbCrLf 301 End If 302 303 ' display verbose information when database exception 304 Catch oleDbExceptionParameter As _ 305 System.Data.OleDb.OleDbException 306 307 Console.WriteLine(oleDbExceptionParameter.StackTrace) 308 txtStatus.Text &= oleDbExceptionParameter.ToString 309 End Try 310 311 End Sub ' Display 312 313 ' clears text boxes 314 Private Sub ClearTextBoxes() 315 txtFirst.Clear() The Clear button clears the text from the TextBox es using method ClearTextBoxes
69
2002 Prentice Hall. All rights reserved. Outline 69 AddressBook.vb 316 txtLast.Clear() 317 txtAddress.Clear() 318 txtCity.Clear() 319 txtState.Clear() 320 txtZip.Clear() 321 txtCountry.Clear() 322 txtEmail.Clear() 323 txtPhone.Clear() 324 txtFax.Clear() 325 End Sub ' ClearTextBoxes 326 327End Class ' FrmAddressBook
70
2002 Prentice Hall. All rights reserved. Outline 70 AddressBook.vb
71
2002 Prentice Hall. All rights reserved. Outline 71 AddressBook.vb
72
2002 Prentice Hall. All rights reserved. Outline 72 AddressBook.vb
73
2002 Prentice Hall. All rights reserved. Outline 73 AddressBook.vb
74
2002 Prentice Hall. All rights reserved. 74 19.8 Reading and Writing XML Files ADO.NET can convert data from data source into XML files –Uses methods WriteXml, ReadXml andGetXml
75
2002 Prentice Hall. All rights reserved. Outline 75 XMLWriter.vb 1 ' Fig. 19.30 XMLWriter.vb 2 ' Demonstrates generating XML from an ADO.NET DataSet 3 4 Public Class FrmXMLWriter 5 Inherits System.Windows.Forms.Form 6 7 ' constructor 8 Public Sub New() 9 MyBase.New() 10 11 ' This call is required by the Windows Form Designer. 12 InitializeComponent() 13 14 ' Add any initialization after the 15 ' InitializeComponent() call 16 17 ' open database connection 18 BaseballConnection.Open() 19 20 ' fill DataSet with data from OleDbDataAdapter 21 BaseballDataAdapter.Fill(BaseballDataSet, "Players") 22 23 ' bind DataGrid to DataSet 24 dgdPlayers.SetDataBinding(BaseballDataSet, "Players") 25 End Sub 26 27 Friend WithEvents cmdWrite As System.Windows.Forms.Button 28 Friend WithEvents dgdPlayers As System.Windows.Forms.DataGrid 29 Friend WithEvents txtOutput As System.Windows.Forms.TextBox 30 Friend WithEvents BaseballConnection As _ 31 System.Data.OleDb.OleDbConnection 32 33 Friend WithEvents BaseballDataAdapter As _ 34 System.Data.OleDb.OleDbDataAdapter 35 Establishes a connection to the Baseball databaseMethod Fill of class OleDbDataAdapter is called to populate BaseballDataSet with data from the Players table in the Baseball database Binds the dgdPlayers to BaseballDataSet to display the information to the user
76
2002 Prentice Hall. All rights reserved. Outline 76 XMLWriter.vb 36 Friend WithEvents BaseballDataSet As System.Data.DataSet 37 38 ' Visual Studio.NET generated code 39 40 ' write XML representation of DataSet when button clicked 41 Private Sub cmdWrite_Click(ByVal sender As System.Object, _ 42 ByVal e As System.EventArgs) Handles cmdWrite.Click 43 44 ' write XML representation of DataSet to file 45 BaseballDataSet.WriteXml("Players.xml") 46 47 ' display XML in TextBox 48 txtOutput.Text &= "Writing the following XML:" & _ 49 vbCrLf & BaseballDataSet.GetXml() & vbCrLf 50 End Sub ' cmWrite_Click 51 52 End Class ' FrmXMLWriter DataSet method WriteXml is invoked to generate an XML representation of the data contained in the DataSet and then writes the XML to the specified file
77
2002 Prentice Hall. All rights reserved. 77 19.8 Reading and Writing XML Documents Fig. 19.31XML document generated from DataSet in DatabaseXMLWriter.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.