Vb.Net and CSV files - vb.net

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.

Related

How to use cmd.parameters.add("#ID") SQL, VB.NET

Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim dt As DataTable = New DataTable()
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM"
Using command As New SqlCommand(sql, conn)
Using adapter As New SqlDataAdapter(command)
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
'command.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(TextBox1.Text)
adapter.Fill(dt)
TextBox1.Text = dt(0)(0)
End Using
End Using
End Using
This code working properly asper my expectation. When I use "where ID=#ID" in sqlcommand It's showing error: 'Input string was not in a correct format.'
Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim dt As DataTable = New DataTable()
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM where ID=#ID"
Using command As New SqlCommand(sql, conn)
Using adapter As New SqlDataAdapter(command)
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
command.Parameters.Add("#ID", SqlDbType.Int).Value = Convert.ToInt32(TextBox1.Text)
adapter.Fill(dt)
TextBox1.Text = dt(0)(0)
End Using
End Using
End Using
In this code I'm getting error. Could someone help me how to declare "#ID". Thank you..
Please check the error description.
enter image description here
That's maybe because you are trying to add parameters using the statement of the adapter.
Try this:
Dim idValue As Int = Convert.ToInt32(TextBox1.Text)
Dim dt As DataTable = New DataTable()
Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM where ID=#ID"
Using command As New SqlCommand(sql, conn)
command.Parameters.Add("#ID", SqlDbType.Int).Value = idValue
Using adapter As New SqlDataAdapter(command)
adapter.Fill(dt)
End Using
End Using
End Using
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
TextBox1.Text = dt(0)(0)
If you want to change the way you using to parse string to int:
Dim idValue As Int = Integer.Parse(TextBox1.Text)
Dim dt As DataTable = New DataTable()
Dim connect As String = "Data Source=DESKTOP-D32ONKB;Initial Catalog=Attendance;Integrated Security=True"
Using conn As New SqlConnection(connect)
Dim sql As String = "SELECT ID,Name,Class,Date FROM stuattrecordAMPM where ID=#ID"
Using command As New SqlCommand(sql, conn)
command.Parameters.AddWithValue("ID", idValue)
Using adapter As New SqlDataAdapter(command)
adapter.Fill(dt)
End Using
End Using
End Using
Dim i As Integer = 0
For i = 0 To dt.Rows.Count - 1
Dim sy As String = dt.Rows(i).Item(0).ToString
Next
TextBox1.Text = dt(0)(0)
it looks like in your broken code you need/want to have multiple "id" or more than one value. You can do this, but you ALSO then have to add the parameters to the source sql string.
You can't just add, or have multiple #ID values for the one "#ID".
If you want more than one ID value in the same sql query, then you have to add multiple "#id1" then "#id2" and so on to the sql text for this to work.
So, if you have ONE "#ID" then fine.
However, if you have say id 2, 134, 222?
Then you would have to add each parmater to the sql string.
You can do it this way:
dim strSQL as string = "SELECT * FROM MyTable"
dim strWhere as string = ""
dim cmdSQL as New Sqlcommand("", new Sqlconneciton("con string here")
' add first #id
strWhere = "#ID1"
cmd.SQL.Paramters.Add("#ID1", SqlDbType.Int).Value = 124
' add 2nd #!id
strWhere &= ",#ID2"
cmd.SQL.Paramaters.Add("#ID2", SqlDbType.Int).Value = 456
' and so on and so on
cmdSQL.CommandText = strSQL & " WHERE ID IN (" & strWhere & ")"
dim rstData as new DataTable()
cmdSQL.conneciton.Open()
rstData.Load(cmdSQL.ExectuteReader())
Note VERY interesting that you can create the sql command object, and are 100% free to add as many new parameters as possible to the cmdSQL object, and EVEN do so without having the sql command/text set for the sql command object.
However, you EVENTUALLY will have to setup/provide/have the sql shoved into that command object. So, build up the multiple "#id1, #id2" etc., and then shove that whole correct sql string into the cmdSQL object, and it will work.
However, as noted, you are 100% free to add as many parameters to the cmdSQL object, and even do so without having the SQL made/set/created for the cmdSQL object. They thus can be created 100% independent of the existing sql string/text (or better said lack of that sql string during the parameter adding process).

Vb.net NO value given for one or more given parameters

Dim cmd As OleDbCommand = New OleDbCommand(Sql, con)
Dim strSql As String = "Select EmpName,Count(EmpName) from tblPO where OrderType='" &
"B2B" & "' and POExpireDate < #LogDate Group By EmpName"
Dim tstDate As DateTime = DateTime.Now
Dim dateAsString As String = tstDate.ToString("dd/MM/yy")
cmd.Parameters.AddWithValue("#LogDate", CType(dateAsString, String))
Dim dtb As New DataTable
Using dad As New OleDbDataAdapter(strSql, con)
dad.Fill(dtb)
End Using
con.Close()
I'm working in VB.NET
NO value given for one or more given parameters
error coming while filling datatable..why...how could I fix this.
pls help
Your problem is that you are passing your strSql and the connection to the data adapter but not the command which is what contains the parameter. Pass the command instead
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Using blocks ensure that your database objects are
'Closed And Disposed even if there Is an error.
Dim dtb As New DataTable
Using con As New OleDbConnection("Your connection string")
Dim strSql As String = "Select EmpName,Count(EmpName) from tblPO where OrderType = 'B2B' and POExpireDate < #LogDate Group By EmpName;"
Using cmd As OleDbCommand = New OleDbCommand(strSql, con)
cmd.Parameters.Add("#LogDate", OleDbType.Date).Value = DateTime.Now
'On the next line pass the command, no need to pass connection
'because it has already been passed to the constructor of the command
Using dad As New OleDbDataAdapter(cmd)
dad.Fill(dtb)
End Using
End Using
End Using
End Sub

How to extract data from Access db and place it into a text box using vb.net?

Hi guys I'm trying to search an employee information using SQL from MS Access, and hoping to put the fname lname and such details in their respective textbox which correspond to a specific employee's ID number. I have managed to make the SQL work but I don't know how to extract files from my sql statement and place it inside .text(text box), can you please guide me? Thanks
Here is my code so far:
(UPDATED my code) got an error message : Additional information: ExecuteReader: Connection property has not been initialized. Highlighting Reader below. How can i fix this? I'm trying to extract data and place it into the textbox? Thanks
Private Sub eNumText_SelectedIndexChanged(sender As Object, e As EventArgs) Handles eNumText.SelectedIndexChanged
Dim dbSource = "Data Source= C:\Databse\Company_db.accdb"
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
Dim sqlQuery As String
Dim sqlCommand As New OleDbCommand
Dim sqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
sqlQuery = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
With sqlCommand
.CommandText = sqlQuery
.Connection = con
.Parameters.AddWithValue("EmpID", empNum)
With sqlAdapter
.SelectCommand = sqlCommand
.Fill(Table)
End With
With DataGridView1
.DataSource = Table
End With
End With
Dim path = "Data Source= C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
QueryData(path, command)
con.Close()
End Sub
Private Sub QueryData(PathDb As String, command As String)
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using da As New System.Data.OleDb.OleDbCommand(command, connection)
connection.Open()
Dim reader = da.ExecuteReader()
If reader.Read() Then
empFnameText.Text = reader("fname")
empLnameText.Text = reader("lname")
End If
connection.Close()
End Using
End Using
End Sub
for this, you need only this classes: Connection, Command, Reader.
Other classes in the code in question, some are redundant and some are required but in complicated than a simple case presentation.
Private Sub QueryData(PathDb As String, command As String)
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using com As New System.Data.OleDb.OleDbCommand(command, connection)
connection.Open()
Dim reader = com.ExecuteReader()
If reader.Read() Then
TextBox1.text = reader("fname")
TextBox2.text = reader("lname")
End If
connection.Close()
End Using
End Using
End Sub
call the method so:
Dim path = "C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
QueryData(path, command)
EDIT - Use parameters:
Private Sub QueryData(PathDb As String, command As String, id As String)
Using connection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & PathDb)
Using com As New System.Data.OleDb.OleDbCommand(command, connection)
com.Parameters.AddWithValue("", id)
connection.Open()
Using reader = com.ExecuteReader()
If reader.Read() Then
TextBox1.Text = reader("fname")
TextBox2.Text = reader("lname")
End If
End Using
connection.Close()
End Using
End Using
End Sub
Call the method:
Dim path = "C:\Databse\Company_db.accdb"
Dim command = "SELECT * FROM tbl_empinfo WHERE EmpID = ?"
Dim empNum = "..."
QueryData(path, command, empNum)

Update Access database records by column, row known

This is what I've got so far :
Dim myCONN As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\Baza.mdb")
Dim cmd1 = New OleDbCommand("SELECT ID FROM Baza WHERE NAZIV=#XXNAZIV")
cmd1.Parameters.AddWithValue("#XXNAZIV", TextBox2.Text)
cmd1.Connection = myCONN
myCONN.Open()
Dim result = cmd1.ExecuteReader()
While (result.Read())
Dim rowx As Integer = GetTextOrEmpty(result("ID"))
End While
I've found the row (rowx) in which I would like to change values in 20 corresponding columns (namesID : NAZIV, SIFRA,...). Data is already presented in textboxes (textbox1...), but I don't know how to finish this code with UPDATE and how to insert changed values back to Access.
Dim cmdText As String = "UPDATE Baza SET NAZIV=#XXNAZIV Where ID=SomeId"
Using con = new OleDbConnection("PROVIDER=Microsoft.ACE.OLEDB.12.0;Data Source = h:\Baza.mdb")
Using cmd = new OleDbCommand(cmdText, con)
con.Open()
cmd.Parameters.AddWithValue("#XXNAZIV",TextBox2.Text)
cmd.ExecuteNonQuery()
End Using
End Using
This should help you to solve your problem, of course you will have to pass ID parameter to query also.
Reference

Tips on file import

Below code is supposed to update a table in oracle with rows imported. But it seems to update all columns in the table with only the first column which is imported from the CSV file. I figure its the "ReadFields" property which needs to manipulated/changed.. PLEASE offer me any suggestions, its urgent.
MsgBox("Saving...")
Dim parser As New FileIO.TextFieldParser("C:\Documents and Settings\test\Desktop\test.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.ColumnCount - 1
**Dim CurrentField = parser.ReadFields()**
Dim sConnectionString As String = "Data Source=TEST;User ID=TEST;Password=TEST;"
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
End Sub
The FileIO.TextFieldParser.ReadFields method parses all the fields in the input string and stores them in an array. In the case above, you should iterate over the individual values in the returned array, but you're always using CurrentField(i). Try using the following to replace the relevant lines above:
cmd.Parameters.AddWithValue("ORDER_NO", CurrentField(0))
cmd.Parameters.AddWithValue("LINE_ITEM_NO", CurrentField(1))
cmd.Parameters.AddWithValue("CONTRACT", CurrentField(2))
cmd.Parameters.AddWithValue("PART_NO", CurrentField(3))
cmd.Parameters.AddWithValue("QTY_REQUIRED", CurrentField(4))
cmd.Parameters.AddWithValue("QTY_PER_ASSEMBLY", CurrentField(5))
Share and enjoy.