2017-04-07 5 views
0

MS Accessテーブルにデータを挿入するにはどうすればよいですか?試してみるとエラーが出ます。MS Accessテーブルにデータを挿入するときのエラー

コード:

If TextBox1.Text = Nothing And TextBox2.Text = Nothing Then 
    MsgBox("No Username and Password inserted") 
    TextBox1.Focus() 

Else 

    If Not con.State = ConnectionState.Open Then 
     'open connection if it is not yet open 
    End If 

    cmd.Connection = con 
    'add data to table 
    cmd.CommandText = "insert into loginTable(username, password, typeofuser) values ('" & Me.TextBox1.Text & "', '" & Me.TextBox2.Text & "', '" & Me.ComboBox1.Text & "')" 

    cmd.ExecuteNonQuery() 

    'refresh data in list 

    'close connection 
    con.Close() 
End If 
+1

どのようなエラーが表示されますか? – stinepike

+0

[VB.NETからMS Accessへのデータの挿入:INSERT INTO文の構文エラー](http://stackoverflow.com/questions/20808528/inserting-data-from-vb-net-to-ms-access) -syntax-error-in-insert-into-statement) – Bugs

+0

リンクを見てください。提供される答えは、あなたが何をしているのかを示すはずです。パラメータを使用します。そして、 '[username]、[password]、[typeofuser]'のように大括弧で囲んでいます。 – Bugs

答えて

1

まず、あなたは接続をオープンしていない:

con.Open() 

次に、passwordreserved word in MS Accessです。あなたは角括弧でpasswordをラップする必要があります:

[password] 

あなたが使用してPARAMATERSの代わりに文字列を連結している。

cmd.Parameters.Add("@username", OleDbType.VarChar).Value = txtUsername.Text 
cmd.Parameters.Add("@password", OleDbType.VarChar).Value = txtPassword.Text 
cmd.Parameters.Add("@typeofuser", OleDbType.VarChar).Value = cmbTypeOfUser.Text 

ルックあなたのTextBoxComboBoxコントロールに適切な名前を与える代わりにTextBox1を使用してで、TextBox2およびComboBox1。離れMsgBoxを使用してMessageBox.Showを使うから

txtUsername 
txtPassword 
cmbTypeOfUser 

移動:これは正しく、各コントロールを識別するのに役立ちます。 MsgBoxはVB6のために存在し、とにかくMessageBoxに委任してしまうので、MessageBox.Showを使用することは理にかなって:

MessageBox.Show("No Username and Password inserted") 

最後に私はあなたのSQLオブジェクトの処分近いとに役立ちますUsingの実装を検討します:

Using cmd As New OleDbCommand(command, connection) 

End Using 

コードをまとめてみると、次のようになります。

If txtUsername.Text = Nothing And txtPassword.Text = Nothing Then 

    MessageBox.Show("No Username and Password inserted") 
    TextBox1.Focus() 

Else 

    Using con As New OleDbConnection(connectionString), 
      cmd As New OleDbCommand("INSERT INTO [loginTable] ([username], [password], [typeofuser]) VALUES (@username, @password, @typeofuser)", con) 

     con.Open() 

     cmd.Parameters.Add("@username", OleDbType.VarChar).Value = txtUsername.Text 
     cmd.Parameters.Add("@password", OleDbType.VarChar).Value = txtPassword.Text 
     cmd.Parameters.Add("@typeofuser", OleDbType.VarChar).Value = cmbTypeOfUser.Text 

     cmd.ExecuteNonQuery() 

    End Using 

End If 

これはこの質問の範囲外ですが、私はパスワードの暗号化も見ていきます。プレーンテキストとして保存するのは悪い習慣です。 SOの質問を見てください。 Best way to store password in database、これはあなたにこれを行うにはどのように最善の方法についていくつかのアイデアを与えるかもしれません。

0

これはいくつかの方法があります。だから、これを試してみてください。 。 。

Imports System.Data.OleDb 

Public Class Form1 

    Private ConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Excel\Desktop\Coding\Microsoft Access\Northwind.mdb;" 
    Private NewIdentifer As Integer = 0 
    Private InsertStatement As String = "INSERT INTO Employee (LName) Values(@LName)" 
    Private IdentifierStatement As String = "Select @@Identity" 

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


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
     Using cn As New OleDbConnection(ConnectionString) 
      Using cmd As New OleDbCommand("SELECT * FROM Employee", cn) 
       Dim dt As New DataTable 
       cn.Open() 
       Dim Reader As OleDbDataReader = cmd.ExecuteReader() 
       dt.Load(Reader) 
       Dim dv = dt.DefaultView 
       DataGridView1.DataSource = dv 
      End Using 
     End Using 
    End Sub 

    'End Sub 

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

     If Not String.IsNullOrEmpty(txtLastName.Text) Then 
      Using cn As New OleDbConnection(ConnectionString) 
       Using cmd As New OleDbCommand(InsertStatement, cn) 
        cmd.Parameters.AddWithValue("@LName", txtLastName.Text) 
        cn.Open() 
        cmd.ExecuteNonQuery() 
        cmd.CommandText = IdentifierStatement 
        NewIdentifer = CInt(cmd.ExecuteScalar()) 
        Dim Row As DataRowView = CType(DataGridView1.DataSource, DataView).AddNew 
        Row("Fname") = NewIdentifer 
        Row("LName") = txtLastName.Text 
        Row.EndEdit() 
        DataGridView1.CurrentCell = DataGridView1(0, DataGridView1.RowCount - 1) 
        txtLastName.Text = "" 
       End Using 
      End Using 
     Else 
      MsgBox("Please enter a name") 
     End If 

    End Sub 
End Class 

また、試してください。 。 。

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:\Users\Ryan\Desktop\Coding\DOT.NET\Samples VB\Insert Into MS Access Table from Textbox\WindowsApplication1\bin\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 
関連する問題