【发布时间】:2021-03-03 13:30:55
【问题描述】:
我想计算表格中每本书的作者数。 我得到的结果不正确。
表 Title_AuthorTest:
ISBN Au_ID2 书 1 - 作者 1, 书 2 - 作者 2, 书 2 - 作者 3,
结果 - 运行代码后:
2 本书有 1 个作者, 0 本书有 2 个作者, 0 本书有 3 个作者, ...
结果应该是:
1 本书有 1 个作者, 1 本书有 2 个作者, 0 本书有 3 个作者, ...
Imports System.Data
Imports System.Data.OleDb
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim BooksConnection As OleDbConnection
Dim ISBNCommand As OleDbCommand
Dim ISBNAdapter As OleDbDataAdapter
Dim ISBNTable As DataTable
'connect to books database
BooksConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=BooksDB.mdb;")
BooksConnection.Open()
'establish Command object
ISBNCommand = New OleDbCommand("Select * from Title_AuthorTest ORDER BY ISBN", BooksConnection)
'establish data adapter / data table
ISBNAdapter = New OleDbDataAdapter()
ISBNAdapter.SelectCommand = ISBNCommand
ISBNTable = New DataTable()
ISBNAdapter.Fill(ISBNTable)
'count authors
Dim Author As Integer
Dim AuthorCount(10) As Integer 'make array
Dim LastISBN As String
LastISBN = ""
'allow up to 10 authors per title
For Author = 1 To 10
AuthorCount(Author) = 0 'set authorcount for all the authors to zero
Next Author
'set to the first author
Author = 1
'check each row for repeated ISBN
Dim MyRow As DataRow
'LastISBN = ISBNTable.Rows(0)("ISBN").ToString 'get first ISBN
For Each MyRow In ISBNTable.Rows 'loop the table
If MyRow.Item("ISBN").Equals(LastISBN) Then
'is ISBN repeated then add Author
Author += 1
Else
'no more authors for this ISBN
AuthorCount(Author) += 1
Author = 1
LastISBN = MyRow.Item("ISBN").ToString 'zet LastISBN op ISBN die je net hebt geconsulteerd
End If
Next
'display results number of books with x authors
For Author = 1 To 10
ListBox1.Items.Add(Str(AuthorCount(Author)) + " Books with" + Str(Author) + " Authors")
Next
'dispose
BooksConnection.Close()
BooksConnection.Dispose()
ISBNCommand.Dispose()
ISBNAdapter.Dispose()
ISBNTable.Dispose()
End Sub
End Class
【问题讨论】:
-
那么,如果一本书有两个作者,那么表格中有两行吗?这不是表示关系书->作者的正确方式。您应该有一个作者表和一个表示书籍和作者之间关系的表。此表包含 ISBN 和 authors 表的外键
-
我一直以这种方式编码:
For Each MyRow as DataRow In ISBNTable.Rows,并在下面加上Dim。以你的方式,我可能错了,但 MyRow 似乎第一次只是一个新行。我的方式,它总是一个新的行。我不确定这是否会改变任何事情,但这是我最先想到的。我可能对for语句如何处理变量有误。 -
您对变量
Author的使用似乎有问题。我建议创建新的 var 的CurrentISBN和AuthorsPerISBN,它们更清楚它们的目的并重新编码。 -
@technonaut 我发现作者可能存在问题。你能帮我修一下吗?我无法理解它。