vb.net创建学生数据库

时间:2015-11-29 04:31:15

标签: database vb.net visual-studio

你好我试着做一些任务,我有一个问题

当我点击创建新学生数据库时,我收到错误

'Binary Formatters for serialization
Imports System.Runtime.Serialization.Formatters.Binary
'File Input/Output object
Imports System.IO
'ADO OleDb objects
Imports System.Data.OleDb

Public Class frmStart

'DbOptions class instance
Dim persistedOptions As New DbOptions
'String object to hold the path and name of the database
Dim dbFile As String

Private Sub initialiseOptions()
    Dim myFileStream As Stream
    'Create a BinaryFormatter object to use in deserializing the serialised file
    Dim deserializer As New BinaryFormatter()
    If File.Exists("DatabaseOptions.bin") Then
        'The file exists so create a file stream object to open the file for reading
        myFileStream = File.OpenRead("DatabaseOptions.bin")
        'Set the instance of the OptionsClass to equal the saved serialized file
        'Note that the deserialized file is conveted to an OptionClass object using CType()
        persistedOptions = CType(deserializer.Deserialize(myFileStream), DbOptions)
        If (dbFile <> "") Then
            'CLose the file stream object
            myFileStream.Close()
            'Set status bar text to display curent DB file name
            tsLblDbName.Text = dbFile
        Else
            'The db file name is blank (database closed) Set status bar text to none
            tsLblDbName.Text = "None Open"
        End If
        myFileStream.Close()
    Else
        'The options file doesn't exist (first time run) Set status bar text to none
        tsLblDbName.Text = "None Open"
    End If
End Sub

Private Sub saveCurrentOptions()
    Try
        persistedOptions.DatabaseName = dbFile
        'Create a file stream object that will create the file named SavedOptions.bin
        Dim myFileStream As Stream = File.Create("DatabaseOptions.bin")
        'Create a BinaryFormatter object to use in creating the serialised file
        Dim serializer As New BinaryFormatter()
        'Create the serialized OptionClass file using the BinaryFormatter object
        serializer.Serialize(myFileStream, persistedOptions)
        'CLose the file stream object
        myFileStream.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub
Public Function CreateNewStudentDatabase(ByVal DatabaseFullPath As String) As Boolean
    Dim cat As New ADOX.Catalog() 'ADOX Catalog object.
    Dim studentTable As New ADOX.Table 'ADOX Table object
    Dim PkIndex As New ADOX.Index 'ADOX Index object (for defining the Primary Key)
    Dim sCreateString As String 'Holds the OLEDB connection string
    Dim success As Boolean 'Flag to indicate create table success or fail
    Try
        sCreateString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DatabaseFullPath
        'The Catalog Create method creates and opens a new ADO Connection using sCreateString
        cat.Create(sCreateString)
        'Add the columns and their definition to the Table Columns collection
        With studentTable
            .Name = "Students"
            .Columns.Append("StudentID", ADOX.DataTypeEnum.adVarWChar, 5)
            .Columns.Append("FirstName", ADOX.DataTypeEnum.adVarWChar, 40)
            .Columns.Append("LastName", ADOX.DataTypeEnum.adVarWChar, 40)
            .Columns.Append("Address", ADOX.DataTypeEnum.adVarWChar, 40)
            .Columns.Append("Suburb", ADOX.DataTypeEnum.adVarWChar, 40)
            .Columns.Append("State", ADOX.DataTypeEnum.adVarWChar, 3)
            .Columns.Append("PostCode", ADOX.DataTypeEnum.adVarWChar, 6)
            .Columns.Append("PhoneNumber", ADOX.DataTypeEnum.adVarWChar, 12)
        End With
        PkIndex.Name = "PrimaryKey" 'Set a name for the Index
        PkIndex.PrimaryKey = True 'Define the Index as a primary key index
        PkIndex.Columns.Append("StudentID") 'Set the StudentID column as the index
        studentTable.Indexes.Append(PkIndex) 'Add the index to Indexes collection of the table
        cat.Tables.Append(studentTable) 'Add the new studentTable to the Tables collection
        success = True 'Flag a successful creation
    Catch Excep As System.Runtime.InteropServices.COMException
        success = False 'Flag a failed database creation
    Finally
        'Clean up.no longer required objects
        studentTable = Nothing
        PkIndex = Nothing
        cat = Nothing
    End Try
    Return success 'Return true or false to indicate success or fail
End Function

Private Sub frmStart_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    initialiseOptions() 'Call sub to read saved options
End Sub

Private Sub mnuFile_Db_NewDb_Click(sender As Object, e As EventArgs) Handles mnuFile_Db_NewDb.Click, btnCreateNewDb.Click
    Dim newFile As New SaveFileDialog 'Create a new SaveFileDialog object
    ' Set the properties on SaveFileDialog
    newFile.CreatePrompt = False
    newFile.OverwritePrompt = False
    newFile.FileName = "New Database"
    newFile.Filter = "Microsoft Access Files |*.accdb" 'filter files by the extension
    newFile.AddExtension = True 'Add extension (.accdb) if omitted by user
    'Set the initial path to My Documents folder
    newFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)

    If newFile.ShowDialog() = DialogResult.OK Then
        dbFile = newFile.FileName
        'Call the function to create the new database
        If (CreateNewStudentDatabase(dbFile)) Then
            saveCurrentOptions() 'Call sub to update saved options
            initialiseOptions() 'Call sub to read saved options
            MessageBox.Show("New blank database " & dbFile & " has been created and is connected.", "Database Created", 0, MessageBoxIcon.Information)
        Else
            MessageBox.Show("Failed to create and connect to new Database file!")

        End If
    End If
End Sub

Private Sub mnuFile_Db_OpenDb_Click(sender As Object, e As EventArgs) Handles mnuFile_Db_OpenDb.Click, btnOpenExistingDb.Click
    Dim openFile As New OpenFileDialog 'Create a new OpenFileDialog object
    openFile.Filter = "Microsoft Access Files |*.accdb" 'Show only files with .accdb extension
    'Set the initial directory to the My Documents folder
    openFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
    openFile.Multiselect = False 'Dissallow multiple file selection
    If (openFile.ShowDialog() = Windows.Forms.DialogResult.OK) Then
        dbFile = openFile.FileName
        saveCurrentOptions() 'Call sub to update saved options
        initialiseOptions() 'Call sub to read saved options
    End If
End Sub

Private Sub mnuFile_Db_CloseDb_Click(sender As Object, e As EventArgs) Handles mnuFile_Db_CloseDb.Click
    dbFile = ""
    saveCurrentOptions()
    tsLblDbName.Text = "None Open"
End Sub

Private Sub mnuFileExit_Click(sender As Object, e As EventArgs) Handles mnuFileExit.Click
    Application.Exit()
End Sub

Private Sub frmStart_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    If (MessageBox.Show("Are you sure you want to exit this application?", "Confrim Exit", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No) Then
        e.Cancel = True

    End If
End Sub

Private Sub btnViewCurrentDb_Click(sender As Object, e As EventArgs) Handles btnViewCurrentDb.Click
    'Check that a database has been opened and stored in variable dbFile
    If (dbFile <> "") Then
        'Create the connection that will be passed over to the Students form
        Dim connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbFile)
        'Create an SQL query to retrieve all student record
        Dim strQuery As String = "SELECT * FROM Students ORDER BY StudentID;"
        Try
            'Create an instance of frmStudents and pass the connection to the constructor
            Dim studentDbForm As New frmStudents(connection)
            'Show form in modal state
            studentDbForm.ShowDialog()
        Catch ex As Exception 'Catch any exception that occurs
            'display error on what most likely went wrong as well as the System error message
            MessageBox.Show("Failed to connect to " & dbFile & vbNewLine &
            "The file may have been moved or deleted. Open an existing database or create a new one." &
            vbNewLine & "System Message:" & vbNewLine & ex.Message, "Database Connection Failed", 0, MessageBoxIcon.Exclamation)
        End Try
    Else
        MessageBox.Show("Please open an existing database or create a new one.", "No Active Database ", 0, MessageBoxIcon.Information)
    End If
End Sub
End Class

0 个答案:

没有答案