使用VB.Net创建MS Access数据库文件,表和字段

时间:2018-06-27 13:57:58

标签: vb.net ms-access

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

2 个答案:

答案 0 :(得分:0)

您可以尝试创建一个ms Access数据库文件。

Dim connectionString As String = _
    "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Data Source=C:\Users\Public\mdbTest.mdb;"
    Using con As New OleDbConnection(connectionString)
con.Open()
Using cmd As New OleDbCommand()
    cmd.Connection = con
    cmd.CommandText = "CREATE TABLE zzzTest (ID COUNTER, VALUES INTEGER)"
    Try
        cmd.ExecuteNonQuery()
        Console.WriteLine("Table created.")
    Catch ex As Exception
        Console.WriteLine(ex.Message)
    End Try
End Using
con.Close()

最终使用

也使用下面的链接来创建数据库和表。

Create database and table

答案 1 :(得分:0)

这里是如何使用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