首页 > 解决方案 > 使用 VB.Net 创建 MS Access 数据库文件、表和字段

问题描述

我想使用 VB.net 编码创建一个数据库文件,数据库文件名为“College1”。在数据库文件“College1”中,我想添加一个名为“StudentList”的表。在表“学生列表”中,我想添加以下字段 1. 学生姓名 2. DOB 3. 课程 4. 手机号码,如果可能的话,我是否可以格式化列,例如 DOB 为日期格式,手机号码为数字格式

标签: vb.netms-access

解决方案


下面是如何使用 VB.NET 创建 MS Access 数据库的示例。

Imports ADOX
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim cat As Catalog = New Catalog()
        cat.Create("Provider=Microsoft.Jet.OLEDB.4.0;" &
                    "Data Source=C:\Users\Excel\Desktop\NewMDB.mdb;" &
                    "Jet OLEDB:Engine Type=5")
        Console.WriteLine("Database Created Successfully")
        cat = Nothing
    End Sub
End Class

注意:需要添加引用'Microsoft ADO Ext 2.8'

而且,这是一个通用示例,说明如何从 VB.NET 中的 TextBox 将数据写入 MS Access。我认为您想做的不仅仅是创建数据库,对...

Imports System.Data.OleDb

Public Class Form1



    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

        ' Requires: Imports System.Data.OleDb

        ' ensures the connection is closed and disposed
        Using connection As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" & _
            "Data Source=""C:\your_path_here\InsertInto.mdb"";" & _
            "Persist Security Info=False")
            ' open connection
            connection.Open()

            ' Create command
            Dim insertCommand As New OleDbCommand( _
                "INSERT INTO Table1([inputOne] , [inputTwo] , [inputThree]) " & _
                "VALUES (@inputOne, @inputTwo, @inputThree);", _
                connection)
            ' Add the parameters with value
            insertCommand.Parameters.AddWithValue("@inputOne", TextBox1.Text)
            insertCommand.Parameters.AddWithValue("@inputTwo", TextBox2.Text)
            insertCommand.Parameters.AddWithValue("@inputThree", TextBox3.Text)
            ' you should always use parameterized queries to avoid SQL Injection
            ' execute the command
            insertCommand.ExecuteNonQuery()

            MessageBox.Show("Insert is done!!")

        End Using

    End Sub
End Class

推荐阅读