Append Datatable in VB - vb.net

I am developing windows app in vb where i want to append values in datatable withen a while loop as given below.
If hscode <> "" Then
da1 = New OleDbDataAdapter("select * from [" & tablename & "] where [ItemNo] like '" & hscode & "%'", myConnection)
da1.Fill(dt2)
dtab = dt2.Clone
dtab.Merge(dt2, True)
Dim l As Integer
l = 0
For l = 0 To dt2.Rows.Count - 1
dtab = dt2.Clone
dtab.ImportRow(dt2.Rows(l))
Next
dt2.Clear()
End If
In the above code when the datatable is populating for the first time its is taking only one row in DTAB datatable. and for the second time it is throwing an error.
Can anybody please tell me how to concatenate two datatable. actually i want to show multiple database values in one gridview depending upon some queries.

I can't see the rest of your code, but as it is now, there is no sense in filling a datatable (dt2), cloning its structure in another table (dtab) and then looping over dt2 rows and import these rows in dtab.
You could simply fill dtab
However, assuming that you need dtab separate from dt2 for other reasons, then I think you could remove practically all of your code if you use the Copy method of the DataTable
If hscode <> "" Then
da1 = New OleDbDataAdapter("select * from [" & tablename & "] where [ItemNo] like '" & hscode & "%'", myConnection)
da1.Fill(dt2)
dtab = dt2.Copy()
dt2.Clear()
End If
Also, I think also that you should change your original query to avoid string concatenation and use a parameterized query like this
....
Dim queryText = "select * from [" & tablename & "] where [ItemNo] like ?"
da1 = New OleDbDataAdapter(queryText, myConnection)
da1.SelectCommand.Parameters.AddWithValue("#p1", hscode & "%")
....
This will avoid problems with Sql Injection and parsing of the hscode value.

Related

MySqlException: Column count doesn't match value count at row 1

I am trying to save multiple data to my database with this code:
repNo = MainForm.StaffMixname.Text.Substring(0, 3) & DateTime.Now.ToString("yyyyMMddhhmmss")
MetroGrid5.DataSource = Nothing
Dim ds As DataSet = New DataSet
Dim Query As String = "SELECT ci.seq_id, CONCAT(ci.lastname, ci.firstname) AS fullname, ci.amountApplied, ci.province, co.kind, co.specifications, co.regOwner, co.location FROM clientinformation ci LEFT JOIN collateraloffered co ON ci.seq_id=co.seq_id WHERE co.kind IS NOT NULL AND ci.province = '" & MetroComboBox8.Text & "' AND ci.seq_id BETWEEN '" & convertedstrFrom.ToString("yyMMdd") & "%' AND '" & convertedstrTo.ToString("yyMMdd") & "%'"
Dim fetch As New MySqlDataAdapter(Query, connect)
fetch.Fill(ds, "collateral")
MetroGrid5.DataSource = ds.Tables("collateral")
If MetroGrid5.Rows.Count > 0 Then
Dim cm As New MySqlCommand
With cm
.Connection = connect
For i As Integer = 0 To MetroGrid5.RowCount - 1
.CommandText = _
"INSERT INTO collateralrpt Values('" & repNo & _
"', '" & MetroGrid5.Rows(i).Cells("seq_id").Value & _
"', '" & MetroGrid5.Rows(i).Cells("fullname").Value & _
"', '" & MetroGrid5.Rows(i).Cells("amountApplied").Value & _
"', '" & MetroGrid5.Rows(i).Cells("kind").Value & _
"', '" & MetroGrid5.Rows(i).Cells("specifications").Value & _
"', '" & MetroGrid5.Rows(i).Cells("regOwner").Value & _
"', '" & MetroGrid5.Rows(i).Cells("location").Value & _
"', '" & MetroGrid5.Rows(i).Cells("province").Value & "')"
.ExecuteNonQuery()
Next
End With
cm.Dispose()
cm = Nothing
With connect
.Close()
.Dispose()
End With
Else
MsgBox("No Data!")
End If
but unfortunately It shows MySqlException Column count doesn't match value count at row 1.
Is there any mistake with the code above? thanks in advance.
If you want to retrieve data from one table(s) and insert into another, just use a single data adapter. You can even do so if the tables are in a different database - you just need a different connection for the SelectCommand and InsertCommand. Only a single connection is required for a single database though. E.g.
Dim selectSql = "SELECT Column1A, Column1B FROM Table1"
Dim insertSql = "INSERT INTO Table2
(
Column2A,
Column2B
)
VALUES
(
#Column2A,
#Column2B
)"
Using connection As New MySqlConnection("connection string here"),
insertCommand As New MySqlCommand(insertSql, connection),
adapter As New MySqlDataAdapter(selectSql, connection) With {.InsertCommand = insertCommand, .AcceptChangesDuringFill = False}
With insertCommand.Parameters
.Add("#Column2A", MySqlDbType.Int, 0, "Column1A")
.Add("#Column2B", MySqlDbType.VarChar, 50, "Column1B")
End With
Dim table As New DataTable
connection.Open()
adapter.Fill(table)
adapter.Update(table)
End Using
There are a few things to note here.
I wrote the SQL code using a single, multiline literal. That is far
more readable that concatenating every line.
I used parameters. That prevents numerous issues that have been
written about ad nauseum so I won't go into it here.
There's no grid control involved here. You can add one and bind the DataTable after calling Fill but that is only so you can see the data. It has nothing to do with the actual code of retrieving and saving.
The connection is opened explicitly. You can normally let a Fill or Update call open and close the connection implicitly but, in this case, we want to perform both operations and closing and reopening the connection in between is an unnecessary overhead.
The disposable objects are created with a Using statement, which means they will be implicitly disposed at the end of the block. That inclides closing the connection.
The AcceptChangesDuringFill property of the data adapter is set to True so that all RowStates are left as Added so that all DataRows are ready to be inserted.

SQL query, field name paseed by reference vb.net

I'm having problems trying to make this work, I have this query on an application that Im writing in vb.net 2012:
Dim strSql As String = " SELECT * FROM Table_Master WHERE field & "'= ('" & txtCadena.Text & "')"
What I need is to have the option to choose the field that I'm querying writing the field name on a textbox.
Maybe something like:
strSql As String = string.format("SELECT * FROM Table_Master WHERE [{0}] = '{1}'", txtField.text, txtFieldValue.text.replace("'","''"))
This should work (only for text, not dates, numbers etc) but you have to know that it is not the best practice.
I finally made it doing this.
Dim Query As String
Dimm DT As DataTable = New DataTable
Query = "select Actual, Description, Unit_of_measurement from Table_ARTIClES WHERE NUMPART = '" & txtPartNum.Text & "'"
Dim Table As SqlDataAdapter = New SqlDataAdapter(Query, conn)
Table.Fill(DT)
lblInventory.Text = DT.Rows(0)("Actual").ToString

Sql query to update new values to column Visual Basic

This is my code:
Dim job As String = TextBoxJobNum.Text
Dim idws As Integer
sqlQuery = "UDATE Equipment SET JobHistory = JobHistory+'" & job & "' WHERE ID = '" & idws & "'"
Dim sqlCmd1 As New SqlCommand(sqlQuery, sqlConn)
If sqlConn.State = ConnectionState.Closed Then sqlConn.Open()
For Each row As DataGridViewRow In DataGridViewEquip.Rows
idws = CInt(row.Cells(0).Value)
sqlCmd1.ExecuteNonQuery()
Next
If sqlConn.State = ConnectionState.Open Then sqlConn.Close()
I get the error "Syntax error near '=' " I have searched everywhere but cant seem to find the
correct Syntax for this line. Any help would be greatly appreciated.
Looks to me like you are just missing a "P" in the word "UPDATE"
sqlQuery = "UPDATE Equipment SET JobHistory = JobHistory+'" & job & "' WHERE ID = '" & idws & "'"
Also I would recommend not setting parameters using string concatenation, but instead use parameters on a SqlCommand object. The reason for this is reducing potential problems such as additional escaping (if the "job" variable contains a "'" for example) or SQL injection.

Q. How to dynamically add queries to a table adapter in Visual Studio

I have setup a Table Adapter in Visual Studio linked to a SQL Server db.
I've followed the MSDN tutorials and I have manually setup some queries for this TA. I think of these queries as "pre_hardcoded". I call these queries using the default code:
Me.ItemFactTableAdapter.My_Pre_Hardcoded_Query(Me.MasterDataSet.ItemFact)
I want to dynamically call data in different configuration (from the same Master Table) and thus I need a lot of these pre-hardcoded queries. So, instead of writing 1k queries I've want to use something like this:
TableName = "ItemFact"
H_Label = "ChainName"
V_Label = "ItemName"
Dim Measure As String = "Volume"
Dim Select_Clause As String = "select distinct " & H_Label & "," & V_Label & ", Sum(" & Measure & ") as " & Measure & " "
Dim From_Clause As String = "from " & TableName & " "
Dim Where_Clause As String = ""
Dim GroupBy_Clause As String = "group by " & H_Label & "," & V_Label
Dim SelectionQuery = Select_Clause & From_Clause & Where_Clause & GroupBy_Clause
Where I can dynamically update the values of "Measure" and the "H" & "V Labels".
The question is: How do I declare this SelectionQuery to be a valid part of the TA so that I can use it like:
Me.ItemFactTableAdapter.SelectionQuery (Me.MasterDataSet.ItemFact)
for dynamic query you need create generic DataAdapter:
Dim da As New SqlDataAdapter(SelectionQuery, Me.ItemFactTableAdapter.Connection)
da.Fill(Me.MasterDataSet.ItemFact)
I still haven't found an answer to my initial question ON HOW TO ADD QUERIES TO A TABLE ADAPTER, but based on #lomed answer I've done a workaround. Thus, instead of filling the TA on 1st load and then pulling data with different queries, I'm updating the whole dataset on each query. I believe this method may be more time-consuming when applied to big datasets, but for now it works.
Dim strConn As String = "Data Source=XXX;Initial Catalog=master;Integrated Security=True"
Dim conn As New SqlConnection(strConn)
Dim oCmd As New SqlCommand(SelectionQuery, conn)
Dim oData As New SqlDataAdapter(SelectionQuery, conn)
Dim ds As New DataSet
and then attach the dataset to objects like:
Chart1.DataSource = ds.Tables("Table1")
instead of:
Chart1.DataSource = Me.ItemFactBindingSource

VB.Net Select-Like query in MS Access not working

I need to show the data from the column 'Purchaser' starting with the text entered in the textbox 'Purchaser' on the form. I am using MS Access 2003 database.
For this I am using the following...
Dim query = "SELECT * FROM Details WHERE [Purchaser] LIKE '" & Purchaser.Text & "*'"
Dim dc = New OleDbCommand(query, cn)
Dim rows = dc.ExecuteNonQuery
cn.Close()
If rows = 0 Then
'Show a form for new entry
Else
Dim oleadap = New OleDbDataAdapter(query, cn)
Dim dset As DataSet = Nothing
oleadap.Fill(dset, "Details")
For i = 0 To rows
Dim purName = dset.Tables("Details").Rows(i).Item("Purchaser").ToString
Dim purAddr = dset.Tables("Details").Rows(i).Item("Address").ToString
'Populate a list
Next
End If
The variable 'rows' always turns out to be zero even if I check for a Purchaser starting with, say A, in the database.
That should be:
Dim query = "SELECT * FROM Details WHERE [Purchaser] LIKE '" _
& Purchaser.Text & "%'"
In MS Access, the wild card is asterisk (*), outside of it, the wildcard is percent (%)
In addition, you have ExecuteNonQuery, but that is not true. You are executing a query, here are a few notes for testing.
Dim query = "SELECT * FROM Details WHERE [Purchaser] LIKE '" _
& Purchaser.Text & "%'"
Dim dc = New OleDbCommand(query, cn)
Dim rows As OleDb.OleDbDataReader
rows = dc.ExecuteReader
If rows.HasRows Then
Do While rows.Read()
Console.WriteLine(rows("Purchaser"))
Loop
End If
Console.ReadLine()
Can you use % instead of *. And another one, use parameter.
Dim query = "SELECT * FROM Details WHERE [Purchaser] LIKE #purc & '%' "
Dim dc = New OleDbCommand(query, cn)
dc.Parameters.AddWithValue("#purc", Purchaser.Text)
Dim rows = dc.ExecuteNonQuery