My SQL select query with condition using list in VB.net - vb.net

I have a MySQL table (variable- exchange) with a column name "symbol" and I have a list of string named "listfinalselection". I want to select all rows where the list contains the cell value of column "symbol". But I got a error that there is an error in my SQL syntax. I can't understand that error. Please help. `
Dim mysqlconn As MySqlConnection
mysqlconn = New MySqlConnection
mysqlconn.ConnectionString = "server=localhost;user id=root;password=1234;database=Share"
mysqlconn.Open()
Dim sql As String = "SELECT * FROM " & exchange & " WHERE Symbol in (" & String.Concat(",", listfinalselection.Select(Function(i) $"'{i}'").ToArray()) & ");"
Dim adapter As New MySqlDataAdapter(sql, mysqlconn)
Dim datatable As New DataTable()
adapter.Fill(datatable)
DataGridView1.DataSource = datatable
DataGridView1.Refresh()
Dim ii As Integer = 0
For Each rw As DataGridViewRow In DataGridView1.Rows
Try
DataGridView1.Rows(ii).Cells(11).Value = listeleventh(listsymbol.IndexOf(DataGridView1.Rows(ii).Cells(3).Value.ToString))
Catch
End Try
ii = ii + 1
Next
End Sub `

Here's how we can properly and securely query MySQL for a list of values:
Dim con = New MySqlConnection("server=localhost;user id=root;password=1234;database=Share")
'NOTE WELL: you still have to make sure that exchange contains no SQL!
Dim cmd As New MySqlCommand("SELECT * FROM " & exchange & " WHERE Symbol in (", con)
For i as Integer = 0 to listfinalselection.Count - 1
cmd.Parameters.AddWithValue("#p" & i, listfinalselection(i))
cmd.CommandText &= "#p" & i & ","
Next i
cmd.CommandText = cmd.CommandText.TrimEnd(","c) & ")"
Dim adapter As New MySqlDataAdapter(cmd)
Dim dt as New DataTable
adapter.Fill(dt)
Please note, before someone quotes the "Can we stop using AddWithValue already" blog, it's irrelevant to mysql

Related

How to Search a String with spaces in between

i am new to VB. so when i run my program and search for the name . i want to search with any spaces in between. For example i want to search " Brian Tracy" like that
i am quite confused on the string function that would do that. Thank you for your help
This is the code am working on
Dim search As String = txtAuthorsName.Text
'Search Sql For Authors Data
Dim conn As New
OleDb.OleDbConnection("Provider=Microsoft.ACE.OleDb.12.0;Data Source=" +
Server.MapPath("~/Access/bookstore.accdb"))
conn.Open()
Dim sql As String = "SELECT AID, authorName, authorSex FROM Authors"
Dim cmd As Object
If searchAuthor.SelectedValue.Equals("Name") Then
If search.Length > 0 Then
Dim keywords As String() = search.Split(" ")
sql = "SELECT * FROM Authors where authorName like '%" & keywords(0) & "%'"
For k As Integer = 1 To keywords.Length - 1
sql += " or authorName Like '%" & keywords(k) & "%'"
Next
End If
cmd = New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#authorName", "%" + txtAuthorsName.Text + "%")
Else
sql += "WHERE authorSex LIKE #authorSex"
cmd = New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#authorSex", "%" + txtAuthorSex.Text + "%")
End If
Dim dbread = cmd.ExecuteReader()
GridView2.DataSource = dbread
GridView2.DataBind()
dbread.Close()
conn.Close()
This is an example on how to filter/search data :
Public Sub FilterData(valueToSearch As String)
'
Dim searchQuery As String = "SELECT * From Users WHERE CONCAT(fname, lname, age) like '%" & valueToSearch & "%'"
Dim command As New SqlCommand(searchQuery, connection)
Dim adapter As New SqlDataAdapter(command)
Dim table As New DataTable()
adapter.Fill(table)
DataGridView1.DataSource = table
End Sub
Private Sub BTN_FILTER_Click(sender As Object, e As EventArgs) Handles BTN_FILTER.Click
FilterData(TextBox1.Text)
Make necessary changes, hope it works

Excel to Sql adding certain rows to sql server

cmd.CommandText = (Convert.ToString("SELECT * From [") & excelSheet) & "] Order By" & columnCompany & "OFFSET 0 ROWS FETCH NEXT 100000 ROWS ONLY "
I am trying to map data form excel to an sql table but the excel table has a lot of records in it, so I run out of memory if I try to add all of the records at once. So what I am trying to do is use this line of code
cmd.CommandText = (Convert.ToString("SELECT * From [") & excelSheet) & "] Order By B OFFSET 0 ROWS FETCH NEXT 100000 ROWS ONLY "
So that 100000 row will be added. Then I intend to clear the data table and do the same only from 100001 to 200000 and so on.
But I cant get this to work correctly, it works fine when it is just SELECT TOP 100000 FROM... but then I dont know how to get the next 100000 record. I think the Order By is where the issue is as I'm not sure how to get the correct column.
Here is my code Below
Private Sub btnMap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMap.Click
'Allows columns to be moved mapped in the correct order
Dim nbColumnsToTransfer As Integer = dgvMapped.Columns.GetColumnCount(1)
Dim indexes As List(Of Integer) = (From column As DataGridViewColumn In dgvLoadedata.Columns.Cast(Of DataGridViewColumn)() _
Take nbColumnsToTransfer _
Order By column.DisplayIndex _
Select column.Index).ToList()
Dim columnCompany As Integer = indexes(0)
Dim columnEmail As Integer = indexes(1)
Dim columnFirstName As Integer = indexes(2)
Dim columnSurname As Integer = indexes(3)
Dim columnPostCode As Integer = indexes(4)
Dim columnTelephone As Integer = indexes(5)
Dim columnEmployeeBand As Integer = indexes(6)
Dim DeleteConnection As New Data.SqlClient.SqlConnection
DeleteConnection.ConnectionString = "Data Source=DC01\SQLEXPRESS;Initial Catalog=YCM;User ID=sa;Password=S0rtmypc!"
DeleteConnection.Open()
Dim sqlDTM As String = "Delete From TempMapped"
Dim command As New SqlCommand(sqlDTM, DeleteConnection)
command.ExecuteNonQuery()
Dim sqlDTSR As String = "Delete From TempSplitReq"
command = New SqlCommand(sqlDTSR, DeleteConnection)
command.ExecuteNonQuery()
DeleteConnection.Close()
If chkContactSplitReq.Checked = True Then
Dim dt As New DataTable()
Using con As New OleDbConnection(conString)
Using cmd As New OleDbCommand()
Using oda As New OleDbDataAdapter()
cmd.CommandText = (Convert.ToString("SELECT * From [") & excelSheet) & "] Order By" & columnCompany & "OFFSET 0 ROWS FETCH NEXT 100000 ROWS ONLY ""
cmd.Connection = con
con.Open()
oda.SelectCommand = cmd
oda.Fill(dt)
con.Close()
End Using
End Using
End Using
Dim connection As String = "Data Source=DC01\SQLEXPRESS;Initial Catalog=YCM;User ID=sa;Password=S0rtmypc!"
Using cn As New SqlConnection(connection)
cn.Open()
Using copy As New SqlBulkCopy(cn)
copy.ColumnMappings.Add(columnCompany, 0)
copy.ColumnMappings.Add(columnEmail, 1)
copy.ColumnMappings.Add(columnFirstName, 2)
copy.ColumnMappings.Add(columnPostCode, 3)
copy.ColumnMappings.Add(columnTelephone, 4)
copy.DestinationTableName = "TempSplitReq"
copy.WriteToServer(dt)
End Using
End Using
Dim SplitConnection As New Data.SqlClient.SqlConnection
SplitConnection.ConnectionString = "Data Source=DC01\SQLEXPRESS;Initial Catalog=YCM;User ID=sa;Password=S0rtmypc!"
SplitConnection.Open()
Dim sqlSplit As String = "TempSplitReq_SaveToMapped"
Dim commandSplit As New SqlCommand(sqlSplit, SplitConnection)
commandSplit.ExecuteNonQuery()
SplitConnection.Close()
Else
Dim dt As New DataTable()
Using con As New OleDbConnection(conString)
Using cmd As New OleDbCommand()
Using oda As New OleDbDataAdapter()
cmd.CommandText = (Convert.ToString("SELECT * From [") & excelSheet) + "] "
cmd.Connection = con
con.Open()
oda.SelectCommand = cmd
oda.Fill(dt)
con.Close()
End Using
End Using
End Using
Dim connection As String = "Data Source=DC01\SQLEXPRESS;Initial Catalog=YCM;User ID=sa;Password=S0rtmypc!"
Using cn As New SqlConnection(connection)
cn.Open()
Using copy As New SqlBulkCopy(cn)
copy.ColumnMappings.Add(columnCompany, 0)
copy.ColumnMappings.Add(columnEmail, 1)
copy.ColumnMappings.Add(columnFirstName, 2)
copy.ColumnMappings.Add(columnSurname, 3)
copy.ColumnMappings.Add(columnPostCode, 4)
copy.ColumnMappings.Add(columnTelephone, 5)
copy.DestinationTableName = "TempMapped"
copy.WriteToServer(dt)
End Using
End Using
End If
MsgBox("Data Mapping Complete")
End Sub
A SqlBulkCopy object has a BatchSize property. I have a similar situation and set
copy.BatchSize = 1000
And mine works with a large spreadsheet import. Adjust this property in your environment for better performance.

Getting Primary key values (auto number ) VB

I have a database on Access and I want to insert into 2 tables
ReportReq
req_sysino
I want to get the last value of primary key (auto numbered) and insert it into req_sysino
, I am stuck with this code and I dont know how to proccess
Private Function InsertSysInvToDB(intSysInv As Integer) As Integer
Dim strSQLStatement As String = String.Empty
Dim intNoAffectedRows As Integer = 0
Dim con As New OleDb.OleDbConnection("PROVIDER = Microsoft.ace.OLEDB.12.0; Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb")
Dim cmd As OleDb.OleDbCommand
Dim reqnum As String = "Select ##REQ_NUM from ReportReq"
strSQLStatement = "INSERT INTO req_sysino (Req_num, sysinvo_ID)" +
" VALUES (" & reqnum & "','" & intSysInv & ")"
cmd = New OleDb.OleDbCommand(strSQLStatement, con)
cmd.Connection.Open()
intNoAffectedRows = cmd.ExecuteNonQuery()
cmd.Connection.Close()
Return intNoAffectedRows
End Function
this is my insert code that should generate autonumber
Dim dbProvider = "PROVIDER = Microsoft.ace.OLEDB.12.0;"
Dim dbSource = " Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb"
Dim sql = "INSERT INTO ReportReq (Emp_EmpID, Req_Date,Req_expecDate,Req_repnum, Req_name, Req_Descrip, Req_columns, Req_Filtes, Req_Prompts)" +
"VALUES (#reqNUM,#reqName,#reqDescrip,#reqcolumns,#reqfilters,#reqprompts)"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("#EmpID", txtEmpID.Text)
cmd.Parameters.AddWithValue("#reqDate", DateTime.Today)
cmd.Parameters.AddWithValue("#reqExpecDate", DateTime.Parse(txtbxExpecDate.Text).ToShortDateString())
cmd.Parameters.AddWithValue("#reqNUM", txtRep_NUM.Text)
cmd.Parameters.AddWithValue("#reqName", txtRep_Name.Text)
cmd.Parameters.AddWithValue("#reqDescrip", txtbxRep_Desc.Text)
cmd.Parameters.AddWithValue("#reqcolumns", txtbxColReq.Text)
cmd.Parameters.AddWithValue("#reqfilters", txtbxFilReq.Text)
cmd.Parameters.AddWithValue("#reqprompts", txtbxPromReq.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Immediately after you ExecuteNonQuery() your INSERT INTO ReportReq ... statement you need to run a
SELECT ##IDENTITY
query and retrieve its result, like this
cmd.ExecuteNonQuery() ' your existing statement to run INSERT INTO ReportReq
cmd.CommandText = "SELECT ##IDENTITY"
Dim newAutoNumberValue As Integer = cmd.ExecuteScalar()

Syntax error (comma) in query expression, header with commas

I am trying to check if value from label1 exist in dbf file column named : "NALOG,C,8". Header in DBF file I can not change, 'cause it represents column's format and field size. But with that I get this error : "Syntax error (comma) in query expression "NALOG,C,8 = #NAL"
Here is complete code :
Dim con As New OleDbConnection
Dim cmd As New OleDbCommand
Dim FilePath As String = "C:\"
Dim DBF_File As String = "PROMGL"
Dim ColName As String = "NALOG,C,8"
'Dim SQLstr As String = "SELECT * FROM " & DBF_File
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FilePath & _
" ;Extended Properties=dBASE IV;User ID=Admin;Password="
'cmd = New OleDbCommand("SELECT * FROM " & DBF_File)
cmd = New OleDbCommand("SELECT * FROM PROMGL WHERE " & ColName & " = #NAL")
cmd.Connection = con
con.Open()
cmd.Parameters.AddWithValue("#NAL", Label1.Text)
Using reader As OleDbDataReader = cmd.ExecuteReader()
If reader.HasRows Then
con.Close()
Label6.Text = "EXIST" & TextBox1.Text
TextBox1.Text = ""
TextBox1.Focus()
Else
Label6.Text = "DOESN'T EXIST"
End If
end using
Thanks.
If you have a column that is named this:
Dim ColName As String = "NALOG,C,8"
Then I would change it too this:
Dim ColName As String = "[NALOG,C,8]"
Use this instead:
Dim ColName As String = "NALOG"

DataAdapter update error from InsertCommand

I was doing a bit of refactoring today and suddenly my code to insert/update a database table which has been working for as long as I can remember, is not longer working and is throwing the following error:
InvalidOperationException: Update requires a valid InsertCommand when passed DataRow collection with new rows.
The code is as follows:
' Update a field if it exists or insert a new row
' (should be an insert 99.99% of the time but not guaranteed)
Public Sub InsertOrUpdateValues(... multiple parameters ...)
Dim da As New SqlDataAdapter
Dim dt As New DataTable()
Dim dr As DataRow
Dim commandText As String = "select * from Table_Name where Col_Name1 = '" & value1 & "' AND Col_Name2 = '" & value2 & "'"
Dim sqlCommand As New SqlCommand(commandText, connection)
da.SelectCommand = sqlCommand
da.Fill(dt)
If dt.Rows.Count = 0 Then
dr = dt.NewRow()
dt.Rows.Add(dr)
Else
dr = dt.Rows(0)
End If
dr("Col_Name3") = value3
' ... more of these assignments ...
dr("Col_NameN") = valueN
da.Update(dt)
End Sub
I'm not sure what happened to break the code. I've looked at this MSDN link but I'm not sure how to apply it to the way I have things done with the DataTable. Is there a "best practice" way to do this?
I guess I should have done a little more searching first as I found an answer using CommandBuilder
Dim commandBuilder As New SqlCommandBuilder(da)
If dt.Rows.Count = 0 Then
dr = dt.NewRow()
dt.Rows.Add(dr)
da.InsertCommand = commandBuilder.GetInsertCommand(True)
Else
dr = dt.Rows(0)
da.UpdateCommand = commandBuilder.GetUpdateCommand(True)
End If
I've also added constants for my Table/Column names for easier maintenance and am now using queries with parameters.
Const commandText As String = "select * from " & Table.Name & " where " & Table.Column1 & " = #Value1 AND " & Table.Column2 & " = #Value2"
Dim sqlCommand As New SqlCommand(commandText, _connection)
sqlCommand.Parameters.Add("#Value1", SqlDbType.Type).Value = value1
sqlCommand.Parameters.Add("#Value2", SqlDbType.Type).Value = value2
This should be a bit better but I'm still open to more suggestions if you still want to comment.