如何将数据从表单中的文本框传输到访问表

时间:2015-09-29 18:26:18

标签: vb.net visual-studio textbox ms-access-2007

我目前正在尝试为具有文本框的表单编写代码,以便用户输入所需的数据,然后使用按钮将文本框中的数据发送到访问表。

如果您需要更多信息来帮助解决问题,我愿意提供它,如果您提出要求(我会上传图片/截图,但我需要" 10声誉"显然。

1 个答案:

答案 0 :(得分:0)

你可以这样做

Imports System.Data.OleDb

Public Class Form1
Dim AccessConection As OleDbConnection

Private Sub btSave_Click(sender As Object, e As EventArgs) Handles btSave.Click
    Dim cmd As New OleDbCommand
    Dim mySql As String

    mySql = "INSERT INTO Customs (CustomName,Address) VALUES(@Name,@Address)"

    Try
        cmd.Parameters.AddWithValue("@Name", txName.Text)
        cmd.Parameters.AddWithValue("@Address", txAddress.Text)

        cmd.Connection = AccessConection
        cmd.CommandType = CommandType.Text
        cmd.CommandText = mySql
        cmd.ExecuteNonQuery()

    Catch ex As Exception
        MessageBox.Show("Whatever you want to say..." & vbCrLf & ex.Message)
    End Try
End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim myDataBasePath As String = "C:\Users\user\Source\Workspaces\......\SOF003\Data.accdb" 'Here you put the full name of the database file (including path)
    'The next line is for Access 2003 .mdb files
    'Dim CadenaConection As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}", myDataBasePath)
    Dim CadenaConection As String = String.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0}", myDataBasePath)
    AccessConection = New OleDbConnection(CadenaConection)
    AccessConection.open()
End Sub

结束班

btSave是命令按钮。 海关是表的名称。 CustomName和Address是两个字段。 txName和txAddress是两个TextBox控件。

显然你应该小心数据类型(这里我只使用字符串),验证等等......但是,这是一个起点。如果你搜索,你会找到另外的方法,更详细。