LuckyLuke82 LuckyLuke82 - 4 months ago 39
Vb.net Question

Insert textbox values to Oracle DB

I've never done INSERT statement to Oracle in VB.NET, so I need a little help. My code doesn't work, after executing nothing happens - no errors and no Insert. What is wrong or what am I missing here ? (Field1 and Field2 are just table fields, not a primary key).

Imports System.Data
Imports Oracle.DataAccess.Client ' ODP.NET Oracle managed provider
Imports Oracle.DataAccess.Types

Public Class Save_Records

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

Const conn As String = "Data Source=MyDB;User Id=Lucky;Password=MyPassword;"

Using cn As New OracleConnection(conn)

cn.Open()

Using cmd As New OracleCommand()
cmd.CommandText = "INSERT into MyTable (Field1,Field2) values('" & TxtField1.Text & "','" & TxtField2.Text & "')"
cmd.ExecuteNonQuery()

End Using

End Using

End Sub

End Class

Answer

This method is a starting place for how to insert into Oracle

Private Function insertRow(connectionString As String) As Boolean

    Using cn As OracleConnection = New OracleConnection(connectionString)

        cn.Open()

        Using cmd As OracleCommand = New OracleCommand()

            Const sql As String = "Insert into test_table (val1, val2) values (:var1, :var2)"
            cmd.Connection = cn
            cmd.Parameters.Add(New OracleParameter("var1", TxtField1.Text))
            cmd.Parameters.Add(New OracleParameter("var2", TxtField2.Text))
            cmd.CommandText = sql
            cmd.ExecuteNonQuery()

        End Using

    End Using

End Function