版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
1、DatabaserIntroduksjon til DatabaserResten av foilene fra kap 10.1 som vi gr gjennom p neste forelesningChapter 10 Database Management10.1 An Introduction to Databases10.1 An Introduction to DatabasesDatabase ExplorerAccessing a Database with a Data TableSample Table Cities TableSample Table Countrie
2、s TableDatabase TerminologyA table is a rectangular array of data. Each column of the table, called a field, contains the same type of information.Each row, called a record, contains all the information about one entry in the database. Database Management Software (DBMS)Used to create databasesDatab
3、ases can contain one or more related tablesExamples of DBMS include Access and OracleSe databasen fra Visual BasicDatabase ExplorerThe Standard and Professional editions of Visual Basic contain Server Explorer that also allows the programmer to view information located on other computers.We will foc
4、us on Database Explorer. However, with slight modifications, our discussion applies to Server Explorer.Using the Database Explorerside 513Click on Database Explorer from the View Menu.The Explorer will appear on the left side of the screen.Right-click on “Data Connections”, and select “Add Connectio
5、n”.Set the Data Source to “Microsoft Access Database File.”Click on the “Browse ” button and select the file MEGACITIES.MDB from the folder ProgramsCh10MajorDatabases, and press Open.Clear the contents of the “User name” text box.Database Explorer continuedPress the Test Connection button. The messa
6、ge box stating “Test Connection Succeeded” will appear. Press the OK button on that message box, and then press the OK button on the Data Link Properties box.An icon should appear in Database Explorer. Click on the + sign to the left of the icon to expand this entry. four subentries will appear: Tab
7、les, Views, and Stored Procedures, and Functions.Expand the Tables entry to reveal the subentries, the tables Cities and Countries. Expand an entry to reveal the fields of the table. (See next slide: Figure 10.1)Double-click on a table to show the table in a grid. (See slide two pages ahead: Figure
8、10.2)Figure 10.1 Database ExplorerFigure 10.2 The Cities TableVi lager et VB program som henter data fra en databaseBruker et DataTable object i VBDataTable object er en tabellVi har sett p tabeller med en kolonne og mange rekkerF.eks.: Dim biler() As BilBMW, 325, 1999VW, Caravele, 1997Toyoa, Landcr
9、uiser, 2000. henter data fra en databaseTabeller ha:mange kolonner og mange rekker (todimensjonale)en egen tabell med todimensjonale tabeller! (tredimensjonale)osv. i prinsippet i det uendelige!I INF150 ser programmerer skal vi beherske endimensjonale og kjenne til todimensjonaleTabeller med flere e
10、nn to dimensjoner benyttes sjeldenTodimensjonale tabeller(7.5 Two-dimensional Arrays p.377)Hittil har vi sett p endimensjonale tabeller hvor hvert felt kan inneholde:Enkle verdierStrukturerAlle felt m vre av samme typeN ser vi p todimensjonale tabellerOgs her m alle felt m vre av samme typeF.eks. Bi
11、lannonseMerke, Modell, Arsmodell, AnnonseSattInn, AntVisningerEksempel p todimmensjonal tabellBilannonseMerkeModellArsmodellAnnonseSattInnAntVisningerBMW325199917.11.20069VWCaravelle199711.4.200618ToyotaLandcruiser200020.8.200628Oppgave: Indiker hva som er et “Field” og en “Record” Todimensjonal tab
12、ell i Visual BasicDeklarerer tabell med 10 rekker og 5 kolonner:Dim bilannonse(9, 4) As String Legger inn verdier i kolonnene i rekke 0:bilannonse(0,0) = “BMW”bilannonse(0,1) = “325”bilannonse(0,2) = “1999”bilannonse(0,3) = “17.11.2006”bilannonse(0,4) = “9” Legger inn verdier i kolonnene i rekke 1:b
13、ilannonse(1,0) = “VW”MsgBox(bilannonse.Length)Alle feltene var av type StringDet er vanlig at databaser lagrer alle data som StringVi kan gi tilleggsopplysninger til databasen om hvilken type teksten representerer slik at de som leser databasen kan omforme til rett typeVi legger tabellen inn i Micro
14、soft Access og leser den inn i et VB programStart Access .Opprett BILANNONSER.MDBLag annonser-tabellLegg inn de tre annonseneStart Visual Basicpne for tilgang til DataObject .“Data Table Object”Et “DataTable object” er et ferdig Visual Basic objekt som inneholder en kopi av innholdet i en databaseta
15、bell.En DataTable ligner en vanlig todimensjonal tabell i VB med kolonner og rekker.pne for tilgang til DataObjectVB har mange ferdige objekter og kontroller.Koden til alle er svrt omfattende, s det er bare de vanligste som er tatt med som standard.Vi m derfor gi beskjed dersom vi vil benytte det so
16、m ikke er standard, s som DataObjectGi beskjed om ta med koden til DataObject (se de neste slides)I VB-editoren: Ta med koden til DataObject, denne finnes i System.Data.dll and System.Xml.dll (se side 521:)a) Click on Project in the Menu bar.b) Click on Add Reference in the drop-down menu. To invoke
17、 the “Add Reference” dialog box.c) Make sure the .NET tab is selected.d) Click on System.Data. Hold down the Ctrl key and click on System.Xml.e) Press the OK button.I koden vrI kodevinduet, helt p toppen:Imports System.DataPublic Class Form1 .End ClassConnecting with a DataTableside 521Dim dt As New
18、 DataTable()Dim connStr As String = _ Provider=Microsoft.Jet.OLEDB.4.0; & _ Data Source=MEGACITIES.MDBDim sqlStr As String = SELECT * FROM CitiesDim dataAdapter As New _ OleDb.OleDbDataAdapter(sqlStr, connStr)dataAdapter.Fill(dt)dataAdapter.Dispose()Linje 1 forrige sideDim dt As New DataTable()Dekla
19、rerer dt som en variable av type DataTableLinje 2Dim connStr As String = _ Provider=Microsoft.Jet.OLEDB.4.0; & _ Data Source=MEGACITIES.MDBAngir DatabasedriverenFilespec til databasefilenforutsetter at filen ligger i bin/debug katalogenLinje 3Dim sqlStr As String = SELECT * FROM CitiesSier hvilken t
20、abell data skal hentes fraSQL: Standard Query LanguageLinje 4Dim dataAdapter As New _ OleDb.OleDbDataAdapter(sqlStr, connStr)DB er p disken mens DataTable er i minnetAdapter inneholder kode som omformer vr foresprsel gitt i sqlstr til kode tilpasset databasen gitt i connStrLinje 5 og 6dataAdapter.Fi
21、ll(dt)dataAdapter.Dispose()Bruker DataAdapter til hente data fra DB til tabellen i dtDispose() kalles nr vi ikke har bruk for tilkoblingen mer.Kode for hente fra DBImports System.DataPublic Class Form1 Dim dt As New DataTablePrivate Sub btnTest_Click(.) Handles btnTest.Click Dim connStr As String =
22、Provider=Microsoft.Jet.OLEDB.4.0; & _ Data Source=BILANNONSER.MDB Dim sqlStr As String = SELECT * FROM Annonser Dim dataAdapter As New OleDb.OleDbDataAdapter(sqlStr, connStr) dataAdapter.Fill(dt) dataAdapter.Dispose() . se neste side Kode for hente fra DB lstVis.Items.Add(”Ant. rekker: ” & dt.Rows.C
23、ount) lstVis.Items.Add(”Ant. kolonner: ” & dt.Columns.Count) lstVis.Items.Add(”Rekke 0 kolonne 0: ” & dt.Rows(0)(0) lstVis.Items.Add(”Rekke 0 kolonne modell: ” dt.Rows(0)(modell)End SubDim fmtStr As String = 0,-151,-152,-53,114,5”For i As Integer = 0 To dt.Rows.Count - 1 lstVis.Items.Add(String.Form
24、at(fmtStr, dt.Rows(i)(0), dt.Rows(i)(1),_ dt.Rows(i)(2), dt.Rows(i)(3), dt.Rows(i)(4)NextUtskrift til listbox formateres:Tabell med 3 rekker og 5 kolonner:Dim bilannonse(2, 4) As StringKopierer fra DataTable, dt:bilannonse(0, 0) = dt.Rows(0)(0) . Kode for hente fra DataObject til vr egen todimenjona
25、le tabellProperties of the DataTableside 522After the six lines of code are executed, the number of records in the table is given by dt.Rows.CountThe number of columns in the table is given by dt.Columns.CountThe records are numbered 0 through dt.Rows.Count 1The fields are numbered 0 through dt.Colu
26、mns.Count 1.The name of the jth field is given by dt.Columns(j)The entry in the jth field of the ith record is dt.Rows(i)(j)The entry in the specified field of the ith record is dt.Rows(i)(fieldName)Example 1: FormDisplay one record at a time from the Cities table.Example 1: Partial CodeDim dt As Ne
27、w DataTable()Dim rowIndex As Integer = 0Private Sub frmCities_Load(.) Handles _ MyBase.Load (Last five statements of boilerplate) UpdateTextBoxes()End SubSub UpdateTextBoxes() Display contents of row specified by rowIndex variable txtCity.Text = CStr(dt.Rows(rowIndex)(city) txtCountry.Text = CStr(dt
28、.Rows(rowIndex)(country) txtPop2005.Text = CStr(dt.Rows(rowIndex)(pop2005) txtPop2015.Text = CStr(dt.Rows(rowIndex)(pop2015)End SubExample 1: Partial Code cont.Private Sub btnNext_Click(.) Handles btnNext.Click Show the next record if current one is not the last If (rowIndex 0) Then rowIndex = rowIn
29、dex - 1 UpdateTextBoxes() End IfEnd SubExample 1: Partial Code cont.Private Sub btnFind_Click(.) Handles btnFind.Click Dim cityName As String Dim cityFound As Boolean = False cityName =InputBox(Enter name of city to search for.) For i As Integer = 0 To (dt.Rows.Count - 1) If CStr(dt.Rows(i)(city) =
30、cityName Then cityFound = True rowIndex = i UpdateTextBoxes() End If Next If (Not cityFound) Then MsgBox(Cannot find requested city,0,Not in Table) End IfEnd SubExample 1: OutputExample 2: FormDisplay Cities table along with percentage growth.Example 2: CodePrivate Sub btnShow_Click(.) Handles btnSh
31、ow.Click Dim fmtStr As String= 0,-151,-102,7:N13,7:N14,7:P0 Dim percentIncrease As Double (Six statements of boilerplate) lstDisplay.Items.Add(String.Format(fmtStr, CITY, _ COUNTRY, 2005, 2015, INCR.) For i As Integer = 0 To dt.Rows.Count - 1 percentIncrease = (CDbl(dt.Rows(i)(pop2015) - _ CDbl(dt.Rows(i)(pop2005) / CDbl(dt.Rows(i)(pop2005)
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 安装工程合同的订立与执行3篇
- 常用合同模板3篇
- 文化馆建设方案提案3篇
- 排水沟施工合同范本3篇
- 招标文件认同度评估分析及评估报告3篇
- 工业购销合同3篇
- 排水工程招标要求3篇
- 教育贡献协议3篇
- 市场咨询服务合同示范3篇
- 住宅小区挖掘机施工协议
- 2023年《思想道德与法治》期末考试复习题库(带答案)
- 江苏省南通市崇川区启秀中学2021-2022学年九年级上学期期末物理试卷
- 2021-2022学年四川省成都市高新区人教版四年级上册期末考试数学试卷(原卷版)
- 仓库整改报告PPT
- 堤防工程施工规范
- 陶艺课程讲义
- 【实用文档】生产制造过程流程图
- 四年级奥数之等量代换(含答案)
- 儿科门诊运用PDCA循环降低静脉续加液体漏输率持续改进案例
- 手术室护理实践指南侧卧位的摆放
- 苏少版八年级美术上册《盛世汴梁》教案及教学反思
评论
0/150
提交评论