Check if Row is already exist in table before inserting - vb.net

Well its been a while since my last post about saving loops through checkboxlist.So I did manage to check the input before it saved into table, but somehow it couldnt save any data even if wasnt duplicate one.
Wanted to create a function to check if each checkboxlist is already present within the table but I cant manage it because it needs value from this script so I skip it.
Using conn2 As New SqlConnection()
conn2.ConnectionString = ConfigurationManager _
.ConnectionStrings("BackboneConnectionString").ConnectionString()
Using cmd As New SqlCommand
cmd.CommandText = "Insert into EL_MstFunctionalNilai values(#IDFunc, #nik, #IDFuncParent, #IDFuncChild, #IDFuncMtr, '', '', '0')"
cmd.Connection = conn2
conn2.Open()
For Each item As ListItem In CheckBoxList2.Items
If item.Selected Then
'cmd.Parameters.Clear()
Dim urutan As Int32 = GetNumberFunctional()
Dim str As String = item.Value.ToString
Dim strArr() As String = str.Split("_")
Dim IDFunctionalParent1 As String = strArr(0)
Dim IDFunctionalChild1 As String = strArr(1)
Dim IDFunctionalMtr1 As String = strArr(2)
cmd.CommandText = "select count(*)as numrows from el_mstFunctionalnilai where nik = #nik and idfuncmtr = #IDFuncMtr"
cmd.Parameters.AddWithValue("#nik", txtnik.Text)
cmd.Parameters.AddWithValue("#IDFuncMtr", IDFunctionalMtr1)
queryresult = cmd.ExecuteScalar()
If queryresult = 0 Then
cmd.Parameters.Clear()
cmd.Parameters.AddWithValue("#IDFunc", urutan)
cmd.Parameters.AddWithValue("#nik", txtnik.Text)
cmd.Parameters.AddWithValue("#IDFuncMtr", IDFunctionalMtr1) 'mtr
cmd.Parameters.AddWithValue("#IDFuncParent", IDFunctionalParent1) 'parent
cmd.Parameters.AddWithValue("#IDFuncChild", IDFunctionalChild1) 'child
cmd.ExecuteNonQuery()
'Label1.Text = queryresult --> already check if queryresult has value
End If
End If
Next
conn2.Close()
End Using
End Using
When its executed no error tho, so I cant figure it out what Im missing. Well how do I fix this up?
Thanks.

el_mstFunctionalnilai
EL_MstFunctionalNilai
Which is it? Be careful about capitalization.
I have guessed at all the SqlDbType Please check your database to get the actual types.
Code following your pattern with 2 hits to database.
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim queryResult As Integer
'Pass the connection string directly to the constructor of the connection
Using conn2 As New SqlConnection(ConfigurationManager.ConnectionStrings("BackboneConnectionString").ConnectionString())
'Pass the command text and the connection directly to the command constructor
'You do not need as alias for Count
Using cmd As New SqlCommand("select count(*) from EL_MstFunctionalNilai where nik = #nik and idfuncmtr = #IDFuncMtr", conn2)
conn2.Open()
'This value does not appear to change in the loop so I moved it outside the loop
Dim urutan As Int32 = GetNumberFunctional()
'Add the parameters outside of the loop and only change the value inside the loop
'The value of the text box can't change inside the loop so it can be assigned outside the loop
cmd.Parameters.Add("#nick", SqlDbType.Int).Value = CInt(txtnik.Text)
cmd.Parameters.Add("#IDFuncMtr", SqlDbType.VarChar)
Using cmd2 As New SqlCommand("Insert into EL_MstFunctionalNilai values(#IDFunc, #nik, #IDFuncParent, #IDFuncChild, #IDFuncMtr, '', '', '0')", conn2)
cmd2.Parameters.Add("#IDFunc", SqlDbType.Int).Value = urutan
cmd2.Parameters.Add("#nik", SqlDbType.Int).Value = CInt(txtnik.Text)
cmd2.Parameters.Add("#IDFuncMtr", SqlDbType.VarChar) 'mtr
cmd2.Parameters.Add("#IDFuncParent", SqlDbType.VarChar) 'parent
cmd2.Parameters.Add("#IDFuncChild", SqlDbType.VarChar) 'child
For Each item As ListItem In CheckBoxList2.Items
If item.Selected Then
Dim str As String = item.Value.ToString
Dim strArr() As String = str.Split("_"c)
Dim IDFunctionalParent1 As String = strArr(0)
Dim IDFunctionalChild1 As String = strArr(1)
Dim IDFunctionalMtr1 As String = strArr(2)
cmd.Parameters("#IDFuncMtr").Value = IDFunctionalMtr1
queryResult = CInt(cmd.ExecuteScalar())
If queryResult = 0 Then
cmd2.Parameters("#IDFuncMtr").Value = IDFunctionalMtr1 'mtr
cmd2.Parameters("#IDFuncParent").Value = IDFunctionalParent1 'parent
cmd2.Parameters("#IDFuncChild").Value = IDFunctionalChild1 'child
cmd.ExecuteNonQuery()
End If
End If
Next
End Using
End Using
End Using
End Sub
I think it would be easier using one query that both checks for the existence of the record and inserts it if it doesn't exist.
Protected Sub Method2()
Dim urutan As Int32 = GetNumberFunctional()
Using cn As New SqlConnection(ConfigurationManager.ConnectionStrings("BackboneConnectionString").ConnectionString())
Using cmd As New SqlCommand("If Exists (Select 1 From EL_MstFunctionalNilai where nik = #nik and idfuncmtr = #IDFuncMtr) Select 0 Else Select 1 Insert into EL_MstFunctionalNilai values(#IDFunc, #nik, #IDFuncParent, #IDFuncChild, #IDFuncMtr, '', '', '0');", cn)
cmd.Parameters.Add("#nik", SqlDbType.Int).Value = CInt(txtnik.Text)
cmd.Parameters.Add("#IDFuncMtr", SqlDbType.VarChar)
cmd.Parameters.Add("#IDFunc", SqlDbType.VarChar).Value = urutan
cmd.Parameters.Add("#IDFuncParent", SqlDbType.VarChar)
cmd.Parameters.Add("#IDFuncChild", SqlDbType.VarChar)
cn.Open()
For Each item As ListItem In CheckBoxList2.Items
If item.Selected Then
Dim strArr() As String = item.Value.ToString.Split("_"c)
cmd.Parameters("#IDFuncMtr").Value = strArr(2)
cmd.Parameters("#IDFuncParent").Value = strArr(0)
cmd.Parameters("#IDFuncChild").Value = strArr(1)
cmd.ExecuteScalar()
End If
Next
End Using
End Using
End Sub

Related

Data not showing up in DataGridView after a search query

Hello i am trying to search for data from a table using a funcion, however when i Input the number of the customerID it doesnt show up in the data gridview but the data is still passed to my textboxes. Could anyone help me in explaining what I did wrong?
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
Dim newds As New DataSet
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID =#ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open()
cmd.Parameters.Add("#Fname", DbType.String).Value = Fname
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
Dim da As New SQLiteDataAdapter(cmd)
da.Fill(newds, "customers")
dt = newds.Tables(0)
If dt.Rows.Count > 0 Then
ToTextbox(dt)
End If
dgvCustomerInfo.DataSource = dt
con.Close()
End Using
Return dt
End Function
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
If txtSearchName.Text <> "" Then
SearchData(txtSearchName.Text, "0")
Dim dt = GetSearchResults(txtSearchName.Text)
dgvCustomerInfo.DataSource = dt
ElseIf txtSearchID.Text <> "" Then
SearchData("0", txtSearchID.Text)
Dim dt = GetSearchResults(txtSearchID.Text)
dgvCustomerInfo.DataSource = dt
End If
End Sub
Try to think about what each line of code is doing. See in line comments
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
'Delete this line - there is no need for a Dataset
Dim newds As New DataSet
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID =#ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open() 'Move this line - don't open the connection until directly before the .Execute...
'The Like operator would expect a pattern to match
'The interpolated string with the percent signs add wildcard characters
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{Fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
'Delete - We don't need a DataAdapter
Dim da As New SQLiteDataAdapter(cmd)
'Delete - We already have a filled DataTable
da.Fill(newds, "customers")
'Delete - same as above
dt = newds.Tables(0)
'Delete - Have no idea what this does. You are already going to display your data in a grid
If dt.Rows.Count > 0 Then
ToTextbox(dt)
End If
'Delete - You will set the DataSource in the User Interface code
dgvCustomerInfo.DataSource = dt
'Delete - End Using closes the connection and disposes the connection and command.
con.Close()
End Using
Return dt
End Function
The corrected code will look like this.
Private Function SearchData(Fname As String, ID As Int32) As DataTable
Dim dt As New DataTable
Dim ssql As String = "SELECT * FROM customers WHERE fname LIKE #Fname OR CustomerID =#ID"
Using con As New SQLiteConnection(ConStr),
cmd As New SQLiteCommand(ssql, con)
con.Open()
cmd.Parameters.Add("#Fname", DbType.String).Value = $"%{Fname}%"
cmd.Parameters.Add("#ID", DbType.Int32).Value = ID
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
In the user interface code I have added in line comments.
Private Sub IbtnSearch_Click(sender As Object, e As EventArgs) Handles ibtnSearch.Click
'Declare the DataTable outside the If block
'We do not need a New DataTable because SearchData is returning a DataTable
Dim dt As DataTable
If txtSearchName.Text <> "" Then
'Call only one function to return the DataTable
'SearchData is expecting 2 parameters, a String and an Integer
'Putting 0 in quotes makes it a String
dt = SearchData(txtSearchName.Text, 0)
'I removed the DataSource, Don't repeat yourself
'Assign it once after the If
ElseIf txtSearchID.Text <> "" Then
'The second argument must be an Integer, therefore the CInt()
dt = SearchData("", CInt(txtSearchID.Text))
Else
'Needed to add an Else to assign a value to dt if all else fails
dt = Nothing
End If
dgvCustomerInfo.DataSource = dt
End Sub

Add Column to DataTable before exporting to Excel file

I have a DataTable that is built like this:
Dim dt As New DataTable()
dt = SqlHelper.ExecuteDataset(connString, "storedProcedure", Session("Member"), DBNull.Value, DBNull.Value).Tables(0)
Then it is converted to a DataView and exported to Excel like this:
Dim dv As New DataView()
dv = dt.DefaultView
Export.CreateExcelFile(dv, strFileName)
I want to add another column and fill it with data before I export to Excel. Here's what I'm doing now to add the column:
Dim dc As New DataColumn("New Column", Type.GetType("System.String"))
dc.DefaultValue = "N"
dt.Columns.Add(dc)
Then to populate it:
For Each row As DataRow In dt.Rows
Dim uID As Integer = Convert.ToInt32(dt.Columns(0).ColumnName)
Dim pID As String = dt.Columns(0).ColumnName
Dim qry As String = "SELECT * FROM [MyTable] WHERE [UserID] = " & uID & " AND [PassID] = '" & pID & "'"
Dim myCommand As SqlCommand
Dim myConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
myConn.Open()
myCommand = New SqlCommand(qry, myConn)
Dim reader As SqlDataReader = myCommand.ExecuteReader()
If reader.Read() Then
row.Item("New Column") = "Y"
Else
row.Item("New Column") = "N"
End If
Next row
But I get a "System.FormatException: Input string was not in a correct format." error when I run the app. It doesn't seem to like these lines:
Dim uID As Integer = Convert.ToInt32(dt.Columns(0).ColumnName)
Dim pID As String = dt.Columns(0).ColumnName
I think I have more than one issue here because even if I comment out the loop that fills the data in, the column I created doesn't show up in the Excel file. Any help would be much appreciated. Thanks!
EDIT:
Okay, I was grabbing the column name instead of the actual data in the column... because I'm an idiot. The new column still doesn't show up in the exported Excel file. Here's the updated code:
Dim dt As New DataTable()
dt = SqlHelper.ExecuteDataset(connString, "storedProcedure", Session("Member"), DBNull.Value, DBNull.Value).Tables(0)
Dim dc As New DataColumn("New Column", Type.GetType("System.String"))
dc.DefaultValue = "N"
dt.Columns.Add(dc)
'set the values of the new column based on info pulled from db
Dim myCommand As SqlCommand
Dim myConn As SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
Dim reader As SqlDataReader
For Each row As DataRow In dt.Rows
Dim uID As Integer = Convert.ToInt32(row.Item(0))
Dim pID As String = row.Item(2).ToString
Dim qry As String = "SELECT * FROM [MyTable] WHERE [UserID] = " & uID & " AND [PassID] = '" & pID & "'"
myConn.Open()
myCommand = New SqlCommand(qry, myConn)
reader = myCommand.ExecuteReader()
If reader.Read() Then
row.Item("New Column") = "Y"
Else
row.Item("New Column") = "N"
End If
myConn.Close()
Next row
dt.AcceptChanges()
Dim dv As New DataView()
dv = dt.DefaultView
Export.CreateExcelFile(dv, strFileName)
I suppose that you want to search your MyTable if it contains a record with the uid and the pid for every row present in your dt table.
If this is your intent then your could write something like this
Dim qry As String = "SELECT UserID FROM [MyTable] WHERE [UserID] = #uid AND [PassID] = #pid"
Using myConn = New SqlConnection(ConfigurationSettings.AppSettings("connString"))
Using myCommand = new SqlCommand(qry, myConn)
myConn.Open()
myCommand.Parameters.Add("#uid", OleDbType.Integer)
myCommand.Parameters.Add("#pid", OleDbType.VarWChar)
For Each row As DataRow In dt.Rows
Dim uID As Integer = Convert.ToInt32(row(0))
Dim pID As String = row(1).ToString()
cmd.Parameters("#uid").Value = uID
cmd.Parameters("#pid").Value = pID
Dim result = myCommand.ExecuteScalar()
If result IsNot Nothing Then
row.Item("New Column") = "Y"
Else
row.Item("New Column") = "N"
End If
Next
End Using
End Using
Of course the exporting to Excel of the DataTable changed with the new column should be done AFTER the add of the column and this code that updates it
In this code the opening of the connection and the creation of the command is done before entering the loop over your rows. The parameterized query holds the new values extracted from your ROWS not from your column names and instead of a more expensive ExecuteReader, just use an ExecuteScalar. If the record is found the ExecuteScalar just returns the UserID instead of a full reader.
The issue was in my CreateExcelFile() method. I inherited the app I'm modifying and assumed the method dynamically read the data in the DataTable and built the spreadsheet. In reality, it was searching the DataTable for specific values and ignored everything else.
2 lines of code later, I'm done.

Populate ListBox from SQL only items with condition (first character)

I've managed to put all items in a ListBox, also have the first character defined kto, how to insert only those values from List column into Listbox that begin with that character kto.
Just to mention that kto is value from 0 to 9, always a number.
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
cmd.CommandText = "SELECT List FROM Konta"
Dim kto = Left(Label1.Text, 1)
'Label3.Text = kto
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
Try this
Dim SqlSb As New SqlConnectionStringBuilder()
SqlSb.DataSource = ".\sqlexpress"
SqlSb.InitialCatalog = "Konta"
SqlSb.IntegratedSecurity = True
Using SqlConn As SqlConnection = New SqlConnection(SqlSb.ConnectionString)
SqlConn.Open()
Dim cmd As SqlCommand = SqlConn.CreateCommand()
Dim kto = Left(Label1.Text, 1)
cmd.CommandText = "SELECT List FROM Konta WHERE List LIKE '" & kto.toString & "%'"
ListBox1.Items.Clear
Using reader As SqlDataReader = cmd.ExecuteReader
While (reader.Read())
Me.ListBox1.Items.Add(reader("LIST"))
End While
End Using
SqlConn.Close()
End Using
In your while loop, before adding the item in the listbox check the date type of reader("LIST") and add it only if matches the required type.
You can check the type using the following code:
reader.GetFieldType(0)

need to get value from sql query

Through ADO,I like to do the following query:
select name, address, zip from terr where id = '33334'
I like then to assign name, addess, zip to variables so that I can assign it later in my program.
How do I do this with VB.NET ADO?
Try somethign like this:
Dim dbName As String
Dim dbAddress As String
Dim dbZip As String
Using connObj As New SqlClient.SqlConnection("<connectionString>")
Using cmdObj As New SqlClient.SqlCommand("select name, address, zip from terr where id = '33334'", connObj)
connObj.Open()
Using readerObj As SqlClient.SqlDataReader = cmdObj.ExecuteReader
'This will loop through all returned records
While readerObj.Read
dbName = readerObj("name").ToString
dbAddress = readerObj("address").ToString
dbZip = readerObj("zip").ToString
'handle returned value before next loop here
End While
End Using
connObj.Close()
End Using
End Using
Also, you should look into parameterizing the value for the where clause.
You need a DataBase (i assume MS Sql-Server), a Connection and a DataAdapter to fill a DataTable. Then you have all you need. Here's an example:
Public Function GetUser(UserId As Int32) As DataRow
Using con = New SqlConnection(My.Settings.RM2ConnectionString)
Using cmd = New SqlCommand("select name, address, zip from terr where id = #id", con)
cmd.Parameters.AddWithValue("#id", UserId)
Dim da = New SqlDataAdapter(cmd)
Dim tblUser = New DataTable
da.Fill(tblUser)
If tblUser.Rows.Count <> 0 Then
Return tblUser(0)
Else
Return Nothing
End If
End Using
End Using
End Function
execute a SqlCommand from SQLDatareader, like:
Dim vVendedor As New SqlCommand("SELECT user FROM users", mConeccion)
vDatosVen = vVendedor.ExecuteReader
vVendedor = Nothing
and to get te value:
While vDatosVen.Read()
vUser = vDatosVen("user")
End While
Here's what i did...
Private Sub btn_Connect_Click(sender As Object, e As EventArgs) Handles btn_Connect.Click
Dim sql_connection As New MySqlConnection
Dim sql_query As New MySqlCommand
Dim sql_result As MySqlDataReader
sql_connection.ConnectionString = "Server=localhost;Database=hidden;Uid=root;Pwd=;"
sql_query.Connection = sql_connection
sql_connection.Open()
sql_query.CommandText = "SELECT Entry,name FROM table WHERE entry=1;"
sql_result = sql_query.ExecuteReader
If sql_result.HasRows Then
Do While sql_result.Read()
Dim query_result As String
query_result = sql_result("name")
MsgBox(query_result)
Loop
Else
MsgBox("No results found.")
End If

Vb.Net and CSV files

I have a VB.Net app that should enable the user to import CSV file into the datagrid (which it does) and then update those rows to a table in Oracle.
Here is what I have so far but it doesn't seem to work neither throw an error.
Private Sub Update_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Update.Click
MsgBox("Saving...")
Dim table As New DataTable()
Dim BindingSource As New BindingSource()
BindingSource.DataSource = table
table.Columns.Add("ORDER_NO")
table.Columns.Add("LINE_ITEM_NO")
table.Columns.Add("CONTRACT")
table.Columns.Add("PART_NO")
table.Columns.Add("QTY_REQUIRED")
table.Columns.Add("QTY_PER_ASSEMBLY")
table.Columns.Add("RELEASE_NO")
table.Columns.Add("SEQUENCE_NO")
table.Columns.Add("ORDER_CODE")
table.Columns.Add("PART_OWNERSHIP")
Dim parser As New FileIO.TextFieldParser("C:\Documents and Settings\User\Desktop\solution.csv")
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True
parser.TrimWhiteSpace = True
parser.ReadLine()
Dim sConnectionString As String = "Data
Source=MYSERVER.COM;User ID=MYNAME;Password=MYPASSWD;"
Dim strSql As String = "INSERT INTO SHOP_MATERIAL_ALLOC_TAB(ORDER_NO,
LINE_ITEM_NO, CONTRACT, PART_NO, QTY_REQUIRED, QTY_PER_ASSEMBLY,
RELEASE_NO,SEQUENCE_NO,ORDER_CODE,PART_OWNERSHIP) VALUES (#ORDER_NO,
#LINE_ITEM_NO,#CONTRACT,#PART_NO,#QTY_REQUIRED,#QTY_PER_ASSEMBLY,#RELEASE_NO,#SEQUENCE_NO,#ORDER_CODE,#PART_OWNERSHIP)"
Using conn As New OracleClient.OracleConnection(sConnectionString)
Dim adapter As New OracleDataAdapter
Dim cmd As New OracleClient.OracleCommand()
cmd.Connection = conn
cmd.Connection.Open()
cmd.CommandText = strSql
adapter.InsertCommand = New OracleCommand(strSql, conn)
adapter.UpdateCommand = cmd
adapter.Update(table)
'--cmd.ExecuteReader()
cmd.Connection.Close()
MsgBox("Saved! Kindly check your Shop order!")
DataGridView1.DataSource = Nothing
End Using
End Sub
Now I have brought it down to inserting records in the table, but problem is it only parses the first column in the row.
So all suppose 6 columns in the table are updated with values from the first field in the CSV.
MsgBox("Saving...")
Dim parser As New FileIO.TextFieldParser("C:\Documents and Settings\nUser\Desktop\solution.csv")
parser.Delimiters = New String() {","} ' fields are separated by comma
parser.HasFieldsEnclosedInQuotes = True
parser.TrimWhiteSpace = True
Dim i As Integer
For i = 0 To DataGridView1.RowCount - 1
Dim CurrentField = parser.ReadFields()
'--parser.ReadLine()
Dim sConnectionString As String = "Data Source=MYSERVER.COM;User ID=MYUSER;Password=MYPASSWD;"
Dim strSql As String = "INSERT INTO SHOP_MATERIAL_ALLOCT(ORDER_NO, LINE_ITEM_NO, CONTRACT, PART_NO, QTY_REQUIRED, QTY_PER_ASSEMBLY) VALUES (:ORDER_NO, :LINE_ITEM_NO,:CONTRACT,:PART_NO,:QTY_REQUIRED,:QTY_PER_ASSEMBLY)"
Using conn As New OracleClient.OracleConnection(sConnectionString)
Using cmd As New OracleClient.OracleCommand()
Dim adapter As New OracleDataAdapter
conn.Open()
cmd.Connection = conn
cmd.CommandText = strSql
cmd.Parameters.AddWithValue("ORDER_NO", CurrentField(i))
cmd.Parameters.AddWithValue("LINE_ITEM_NO", CurrentField(i))
cmd.Parameters.AddWithValue("CONTRACT", CurrentField(i))
cmd.Parameters.AddWithValue("PART_NO", CurrentField(i))
cmd.Parameters.AddWithValue("QTY_REQUIRED", CurrentField(i))
cmd.Parameters.AddWithValue("QTY_PER_ASSEMBLY", CurrentField(i))
cmd.CommandText = strSql
adapter.InsertCommand = New OracleCommand(strSql, conn)
adapter.UpdateCommand = cmd
'adapter.Update(table)
cmd.ExecuteNonQuery()
cmd.Connection.Close()
DataGridView1.DataSource = Nothing
End Using
End Using
Next
Never used oracle so please ignore me if I'm being stupid.
Have you tried conn.Connect() rather than cmd.Connection.Open()?
I don't understand the part of your code that create a DataTable and add columns.
It's not used anywhere, so is not related to your issue.
Let's look at code relating data connection
' If I remember well, the parameters in an oracle statement are prefixed by a ":"
Dim strSql As String = "INSERT INTO SHOP_MATERIAL_ALLOC_TAB(ORDER_NO," +
"LINE_ITEM_NO, CONTRACT, PART_NO, QTY_REQUIRED, QTY_PER_ASSEMBLY, " +
"RELEASE_NO,SEQUENCE_NO,ORDER_CODE,PART_OWNERSHIP) VALUES (:ORDER_NO, " +
":LINE_ITEM_NO,:CONTRACT,:PART_NO,:QTY_REQUIRED,:QTY_PER_ASSEMBLY, " +
":RELEASE_NO,:SEQUENCE_NO,:ORDER_CODE,:PART_OWNERSHIP)"
' Connection and Command are Disposable, so use `Using` around them
Using conn As New OracleClient.OracleConnection(sConnectionString)
Using cmd As New OracleClient.OracleCommand()
Dim adapter As New OracleDataAdapter
conn.Open()
cmd.Connection = conn
cmd.CommandText = strSql
' Now you need to add the parameters to your command
' One parameter for each column used in the insert statement
' I suppose that values for the paramenter are in the current line from your CSV
cmd.Parameters.Add("ORDER_NO", OracleType.VarChar).Value = parser[index_of_orderNumber_Text])
' .... other parameters to be added....
' Now you can execute the INSERT statement directly with your command
cmd.ExecuteNonQuery()
End Using
And, as last thing, the OracleClient namespace has been deprecated by Microsoft, so you should try to replace with ODP directly from Oracle.