How to create a query in Visual Studio 2013 using Visual Basic - vb.net

I have the following code and through debugging the problem begins at the While loop. I am trying to retrieve information from 2 tables and insert it into the table created. The information is not being inserted into the table and I am getting blank rows.
Imports System.Data.OleDb
Public Class RouteToCruise
Private Sub RouteToCruise_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Route_Btn_Click(sender As Object, e As EventArgs) Handles Route_Btn.Click
Dim row As String
Dim connectString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=M:\ICT-Group-Project\DeepBlueProject\DeepBlueProject\DeepBlueTables.mdb"
Dim cn As OleDbConnection = New OleDbConnection(connectString)
cn.Open()
Dim CruiseQuery As String = "SELECT CruiseID, RouteID FROM Cruise WHERE CruiseID =?"
Dim RouteQuery As String = "SELECT RouteName FROM Route WHERE RouteID =?"
Dim cmd As OleDbCommand = New OleDbCommand(CruiseQuery, cn)
Dim cmd2 As OleDbCommand = New OleDbCommand(RouteQuery, cn)
cmd.Parameters.AddWithValue("?", Route_Txt.Text)
Dim reader As OleDbDataReader
reader = cmd.ExecuteReader
'RCTable.Width = Unit.Percentage(90.0)
RCTable.ColumnCount = 2
RCTable.Rows.Add()
RCTable.Columns(0).Name = "CruiseID"
RCTable.Columns(1).Name = "Route"
While reader.Read()
Dim rID As String = reader("RouteID").ToString()
cmd2.Parameters.AddWithValue("?", rID)
Dim reader2 As OleDbDataReader = cmd2.ExecuteReader()
'MsgBox(reader.GetValue(0) & "," & reader.GetValue(1))
row = reader("CruiseID") & "," & reader2("RouteName")
RCTable.Rows.Add(row)
cmd.ExecuteNonQuery()
reader2.Close()
End While
reader.Close()
cn.Close()
End Sub
End Class

If I understand your tables structure well then you could just run a single query extracting data from the two table and joining them in a new table returned by the query
Dim sql = "SELECT c.CruiseID c.CruiseID & ',' & r.RouteName as Route " & _
"FROM Cruise c INNER JOIN Route r ON c.RouteID = c.RouteID " & _
" WHERE c.CruiseID = #cruiseID"
Dim cmd As OleDbCommand = New OleDbCommand(sql, cn)
cmd.Parameters.Add("#cruiseID", OleDbType.Int).Value = Convert.ToInt32(Route_Txt.Text)
Dim RCTable = new DataTable()
Dim reader = cmd.ExecuteReader()
reader.Load(RCTable)
At this point the RCTable is filled with the data coming from the two tables and selected using the Route_Txt textbox converted to an integer. If the CruiseID field is not a numeric field then you should create the parameter as of type OleDbType.VarWChar and remove the conversion to integer

Try simplifying your query.
Dim CruiseRouteQuery As String = "SELECT C.CruiseID, C.RoutID, R.Routename FROM Cruise C LEFT JOIN Route R ON C.RouteID = R.RoutID WHERE CruiseID =?"
Also, please let us know what errors you are getting.

Related

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.

Vb.net db issue

I'm writing a calorie counter tool for my girlfriend...
But I've run in to an issue I really cant figure out...
I have place in my script where I would wanna take some information out from my db...
The specific place in the script thats teasing, is the one that will take out data from a row called "antal" from a table called "items".
One place in my script, I call "navn" from items, and it works perfect...
This other place, it gives me the error that there isn't any data in the row!
My code looks so far like this:
Imports System.Data.OleDb
Private Sub ins_kat_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ins_kat.SelectedIndexChanged
Dim Con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Privat\MCC\mccdb.mdb")
Con.Open()
Dim command As OleDbCommand = New OleDbCommand("SELECT * FROM items WHERE kat = '" & ins_kat.Text & "' ORDER BY id DESC", Con)
Dim read As OleDbDataReader = command.ExecuteReader()
ins_mad.Items.Clear()
While read.Read()
ins_mad.Items.Add(read.Item("navn")) '<---- This place works!!!
End While
Con.Close()
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim ialt_c_counter As String
Dim ialt_c_counter_conv As Decimal
Dim ialt_c_counter_conv2 As Decimal
Dim ialt_counter As String
Dim ialt_final As Decimal
Dim Con = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Privat\MCC\mccdb.mdb")
Con.Open()
Dim command1 As OleDbCommand = New OleDbCommand("SELECT * FROM food WHERE dag = '" & stat_dag.Text & "' AND maaned = '" & stat_maaned1.Text & "' AND aar = '" & stat_aar1.Text & "'", Con)
Dim read1 As OleDbDataReader = command1.ExecuteReader()
While read1.Read()
ialt_c_counter = read1.Item("antal")
ialt_c_counter_conv = System.Convert.ToDecimal(ialt_c_counter)
Dim commandX As OleDbCommand = New OleDbCommand("SELECT * FROM items", Con)
Dim reader As OleDbDataReader = commandX.ExecuteReader()
ialt_counter = reader.Item("antal") '<--- THIS ONE is giving me the error!!
ialt_c_counter_conv2 = System.Convert.ToDecimal(ialt_counter)
ialt_final = (ialt_c_counter_conv / 100 * ialt_c_counter_conv2) + ialt_final
End While
Con.Close()
MsgBox(ialt_final)
End Sub
End Class
By now, I want a MsgBox telling me the result of my algorithm, but I don't even get that far cause of the error message...
I guess the error you see is
InvalidOperationException: Invalid attempt to read when no data is present.
You never call Read() on the OleDbDataReader called reader.
Note how you use a While loop to call Read() for read and read1, but not reader (bad variable names, btw).

SELECT statement with JOIN and WHERE clause not returning any data

I have problem with data that needs to be seen on datagridview. Bellow is my code:
Public Class Form3
Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim CONNECT_STRING As String = (...)
Dim cnn As New OleDbConnection(CONNECT_STRING)
cnn.Open()
MsgBox(status_narocila.value)
Dim sql As String = "SELECT artikel.st_artikla, artikel.naziv_artikla, narocilo.kolicina, narocilo.barva_tiska, narocilo.izvedba, narocilo.opombe, narocilo.datum_narocila, narocilo.rok_izdelave, narocilo.status, narocilo.ID FROM (narocilo INNER JOIN artikel ON narocilo.id_artkla = artikel.ID) WHERE(narocilo.ID = '" & status_narocila.value & "')"
Dim cmd As New OleDbCommand(sql, cnn)
Dim da As New OleDbDataAdapter(cmd)
Dim ds As New DataSet
da.Fill(ds, "artikel")
cnn.Close()
DataGridView1.DataSource = ds.Tables("artikel")
End Sub
End Class
Value status.narocila.value is integer, I've tested it and getting right value from it. The code is working fine without WHERE clause.
= '" & status_narocila.value & "')"
should be
= " & status_narocila.value & ")"
no ' on numeric data types.
If narocilo.ID is also an integer, then the problem is you're using text qualifers on an integer field.
Try changing your WHERE clause to:
WHERE(narocilo.ID = " & status_narocila.value & ")"

Get result of MS Access query into textbox in VB.NET

I have a table in MS Access which has a colum named NameC (using ODBC to connect to MS Access)
I want the result of the following query to be saved in a txtField
Dim query = "SELECT NameC FROM Table WHERE ClientID = " & Integer.Parse(clientID)
How to do that in VB.NET?
I have a txtNameC.Text field
I currently was reviewing some sample code and they do:
Dim _consultationTable As DataTable
Public Sub Load()
Dim query = "SELECT * FROM Table WHERE ClientID = " & Integer.Parse(clientID)
Me._consultationTable = DatabaseFunctions.GetDataTable(query)
dvgInfo.Rows.Clear()
For Each dtRow In Me._consultationTable.Rows
dvgInfo.Rows.Add()
dvgInfo.Rows.Add(dvgInfo.RowCount-1).Cells("ColClientID").Value = dtRow("ClientId").ToString()
Next
but I do not want to fill a table I just want to get the result of a query into a text box
How can I do this?
I want to do something like this but just return a value and save it into a textbox
Protected Sub BindData()
strSQL = "SELECT * FROM customer"
Dim dtReader As OdbcDataReader
objCmd = New OdbcCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
'*** BindData to GridView ***'
myGridView.DataSource = dtReader
myGridView.DataBind()
dtReader.Close()
dtReader = Nothing
End Sub
Protected Sub BindData()
strSQL = "SELECT SpecificValue FROM customer where x = y..."
Dim dtReader As OdbcDataReader
objCmd = New OdbcCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()
'*** BindData to GridView ***'
myGridView.DataSource = dtReader
myGridView.DataBind()
dtReader.Close()
dtReader = Nothing
End Sub
use DataReader.populate ur data from database in the datareader & from the the datareader u can use perticular values.
i don't know your code,that's why i m giving one simple example.
here is one example.
imports System.Data.OleDb
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connetionString As String
Dim oledbCnn As OleDbConnection
Dim oledbCmd As OleDbCommand
Dim sql As String
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"
sql = "Your SQL Statement Here like Select * from product"
oledbCnn = New OleDbConnection(connetionString)
Try
oledbCnn.Open()
oledbCmd = New OleDbCommand(sql, oledbCnn)
Dim oledbReader As OleDbDataReader = oledbCmd.ExecuteReader()
While oledbReader.Read
MsgBox(oledbReader.Item(0) & " - " & oledbReader.Item(1) & " - " & oledbReader.Item(2))
End While
oledbReader.Close()
oledbCmd.Dispose()
oledbCnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
End Class

Update a Single cell of a database table in VB.net

I am using MS Access Database. Now I have to update a particular cell value. Here is my code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim str As String
Dim Presc As New System.Text.StringBuilder
Dim prs As String(), j As Integer
prs = Split(txtPrescription.Text, vbCrLf)
For j = 0 To prs.Length - 1
Presc.Append(prs(j))
Presc.Append(",")
Next
Try
str = Trim(lsvCase.SelectedItems(0).Text)
'MessageBox.Show(str)
Dim con As System.Data.OleDb.OleDbConnection
Dim ds As New DataSet
Dim rea As System.Data.OleDb.OleDbDataReader
con = New OleDb.OleDbConnection
Dim da As New System.Data.OleDb.OleDbDataAdapter
con.ConnectionString = "Provider = Microsoft.ACE.OLEDB.12.0; Data Source= F:\Sowmya Laptop Backups\sowdb1.accdb;"
con.Open()
Dim cmd As OleDb.OleDbCommand = con.CreateCommand
cmd.CommandText = "UPDATE Casehistory set Prescription =' " & Presc.ToString() & "'"
rea = cmd.ExecuteReader
cmd.ExecuteNonQuery()
da.FillSchema(ds, SchemaType.Mapped)
da.Update(ds, "Casehistory")
con.Close()
Catch ex As Exception
Finally
End Try
End Sub
This code updates all the cells in that column. I want to update only the particular cell having Case_ID = str
Where I have to add the WHERE clause (WHERE Case_ID = " & str & "
I would use command parameters, neater and prevents the SQL injection issue. Something like:
cmd.CommandText = "UPDATE Casehistory set Prescription =#Presc WHERE Case_ID = #CaseID"
cmd.Parameters.AddWithValue("#Presc", Presc.ToString())
cmd.Parameters.AddWithValue("#CaseID",str)
As an aside, having all this code in the button click event is less than ideal. You might want to investigate structuring your app in a more maintainable way - perhaps with a Data Layer for example.
The Where clause should be appended to the end of the OleDbCommmand.CommandText, where you define the Update statement.