如何使用VB.net在Microsoft访问中使用文本框创建表名

时间:2018-02-04 12:56:17

标签: vb.net visual-studio-2010 ms-access

我的代码需要帮助。

问题是:

我尝试使用VB.net(Visual Studio 2010)在MS Access 2010中创建表格,其中,当我在Textbox1中输入文本并点击button1时创建一个表。其中表的名称位于Textbox1

简而言之,

Textbox1将成为我的桌面名称

Imports System.Data.OleDb
Public Class Form1


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


Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=mdbTest.mdb"

Using con As New OleDbConnection(connectionString)
    con.Open()
    Using cmd As New OleDbCommand()
        cmd.Connection = con
            cmd.CommandText = "CREATE TABLE" & TextBox1.Text & "(ID COUNTER, [Name] INTEGER)"
        Try
            cmd.ExecuteNonQuery()
            Console.WriteLine("Table created.")
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try
    End Using
    con.Close()
End Using
End Sub
End Class

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作,首先检查表是否存在,如果是,则删除表(如果表已存在,则可以修改它以停止创建表)。这可以防止表不存在的运行时异常。有例外的属性,例如HasException和LastException可用于确定失败。

''' <summary>
''' If there are failures anyplace you can get the exception
''' via LastException property
''' </summary>
Public Class AccessOperations
    ''' <summary>
    ''' Targeted database
    ''' </summary>
    Private Builder As New OleDbConnectionStringBuilder With
    {
        .Provider = "Microsoft.ACE.OLEDB.12.0",
        .DataSource = IO.Path.Combine(Application.StartupPath, "Database1.accdb")
    }
    ''' <summary>
    ''' Possible results dependent on how you
    ''' use Createtable which is flexible, as is this
    ''' is one way to use it
    ''' </summary>
    Public Enum CreationResult
        AlreadyExits
        CreatedTable
        EncounteredError
    End Enum
    Protected mHasExeption As Boolean
    Public ReadOnly Property HasException As Boolean
        Get
            Return mHasExeption
        End Get
    End Property
    Protected mException As Exception
    Public ReadOnly Property LastException As Exception
        Get
            Return mException
        End Get
    End Property
    ''' <summary>
    ''' Create table in database pointed to in the Builder object
    ''' </summary>
    ''' <param name="pTableName">Table name to create, no considerations for bad names or with spaces</param>
    ''' <param name="pQuery">Query to create table</param>
    ''' <returns></returns>
    Public Function CreateTable(ByVal pTableName As String, ByVal pQuery As String) As CreationResult
        mHasExeption = False
        Try
            If TableExists(Builder.ConnectionString, pTableName) Then
                DropTable(Builder.ConnectionString, pTableName)
            End If
            Using cn As New OleDbConnection With {.ConnectionString = Builder.ConnectionString}
                Using cmd As New OleDbCommand With {.Connection = cn}
                    cmd.CommandText = pQuery
                    cn.Open()

                    cmd.ExecuteNonQuery()
                    Return CreationResult.CreatedTable

                End Using
            End Using
        Catch ex As Exception
            mException = ex
            mHasExeption = True
            Return CreationResult.EncounteredError
        End Try
    End Function
    ''' <summary>
    ''' Determines if table exists
    ''' </summary>
    ''' <param name="pConnectionString"></param>
    ''' <param name="pTableName"></param>
    ''' <returns></returns>
    Public Function TableExists(ByVal pConnectionString As String, ByVal pTableName As String) As Boolean
        Dim Result As Boolean = False

        Dim dt As DataTable = New DataTable With {.TableName = "test"}

        Using cn As New OleDbConnection(pConnectionString)
            cn.Open()
            dt = cn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})
        End Using


        Dim query = (From F In dt.Rows.Cast(Of DataRow)()
                     Where F.Field(Of String)("TABLE_NAME").ToString = pTableName).FirstOrDefault

        If query IsNot Nothing Then
            Result = True
        End If

        Return Result

    End Function
    ''' <summary>
    ''' Drop an existing table
    ''' </summary>
    ''' <param name="pConnectionString"></param>
    ''' <param name="pTableName"></param>
    ''' <returns></returns>
    Public Function DropTable(ByVal pConnectionString As String, ByVal pTableName As String) As Boolean
        mHasExeption = False
        Dim Result As Boolean = False

        Try
            Using cn As New OleDbConnection(Builder.ConnectionString)
                Dim cmd As New OleDbCommand With {.CommandText = "DROP TABLE " & pTableName, .Connection = cn}
                cn.Open()
                Dim affected = cmd.ExecuteNonQuery()

            End Using

            Result = True

        Catch ex As OleDbException
            mException = ex
            mHasExeption = True
        End Try

        Return Result

    End Function
End Class

表格代码

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim ops As New AccessOperations
    Dim pTableName As String = "Catalogue"
    Dim query As String =
                <SQL>
                    CREATE TABLE <%= pTableName %>
                    (
                        [Id] COUNTER, 
                        [StockCode] TEXT(10), 
                        [AccountNumber] TEXT(6)
                    )
                </SQL>.Value
    Dim result As AccessOperations.CreationResult = ops.CreateTable(pTableName, query)
    MessageBox.Show(result.ToString)
End Sub