Converting VBA function to VB.net to get sql data - sql

I am trying to convert VBA code into VB.net and I have made it to a point but I can't convert resultset into vb.net. RS was 'dim as resultset' in VBA, thought i could just change it to dataset but am getting errors with the '.fields' and other options?
Function GetG(sDB As String, sServ As String, sJob As String) As String
'sDB = Database name, sServ = Server\Instance, path = job.path
Dim conString As String = ("driver={SQL Server};server = " &
TextBox1.Text & " ; uid = username;pwd=password:database = " &
TextBox2.Text)
Dim RS As DataSet
Dim conn As SqlConnection = New SqlConnection(conString)
Dim cmd As SqlCommand
conn.Open()
'This is where my problems are occuring
cmd = New SqlCommand("SELECT [ID],[Name] FROM dbo.PropertyTypes")
Do While Not RS.Tables(0).Rows.Count = 0
If RS.Fields(1).Value = sJob Then
GetG = RS.Fields(0).Value
GetG = Mid(GetG, 2, 36)
Exit Do
End If
DataSet.MoveNext
Loop
conn.Close
End Function

Based on my understanding and some guesswork, here is what I came up with for what I think you're wanting.
As I stated in my comment above, it appears you can just use a WHERE clause to get the exact record you want (assuming a single instance of sJob appears in the name column).
Build the connectionstring off the input arguments, not controls on your form. That is after all why you allow for arguments to be passed along. Also note that there is a SqlCommandBuilder object that may be of interest. But for now
Function GetG(sDB As String, sServ As String, sJob As String) As String
'we'll pretend your connectionstring is correct based off of the sDB and sServ arguments
Dim conStr As String = ("driver={SQL Server};server = " & sServ & " ; uid = username;pwd=password:database = " & sDB)
'Create a connection and pass it your conStr
Using con As New SqlConnection(conStr)
con.Open() 'open the connection
'create your sql statement and add the WHERE clause with a parameter for the input argument 'sJob'
Dim sql As String = "SELECT [ID], [Name] FROM dbo.PropertyTypes WHERE [Name] = #job"
'create the sqlCommand (cmd) and pass it your sql statement and connection
Using cmd As New SqlCommand(sql, con)
'add a parameter so the command knows what #job holds
cmd.Parameters.Add(New SqlParameter("#job", SqlDbType.VarChar)).Value = sJob
'Now that have the command built, we can pass it to a reader object
Using rdr As SqlDataReader = cmd.ExecuteReader
rdr.Read()
'i admin i'm a little confused here on what you are
'trying to achieve so ID may not be what you are
'really wanting to get a substring of.
Return rdr("ID").ToString.Substring(2, 36)
End Using
End Using
End Using
End Function
An example to see if this is working could be to call a messagebox do display the result. For this example, I'm going to pretend that TextBox3 holds the sJob you're wanting. With that knowledge, you could simply do:
MessageBox.Show(GetG(TextBox2.Text, TextBox1.Text, TextBox3.Text))
This should then produce the result in a messagebox.

It seems that you're not filling your DataSet. So, when you try to loop through it, it's uninitialized or empty.
Check this answer to see an example: Get Dataset from DataBase

Related

Syntax error (missing operator) in query expression in OleDb vb.net

Please give me a solution.
I think I made the query code wrong
Private Sub PopulateDataGridView()
Dim query = "select ITM,ITC,QOH,PRS FROM IFG (WHERE QOH > 0 AND ITM = #ITM OR ISNULL(#ITM, '') = '')"
Dim constr As String = "provider=Microsoft.Jet.OLEDB.4.0; data source=C:\Users\ADMIN2\Desktop; Extended Properties=dBase IV"
Using con As OleDbConnection = New OleDbConnection(constr)
Using cmd As OleDbCommand = New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#ITM", cbCountries.SelectedValue)
Using sda As OleDbDataAdapter = New OleDbDataAdapter(cmd)
Dim dt As DataTable = New DataTable()
sda.Fill(dt)
dataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub
Syntax error in FROM clause.
contents of the database
It's a question about SQL syntax, really, and not so much vb.net or oledb.
You had two WHERE clauses, which is invalid SQL. Change the second WHERE to AND
Dim query As String = "select ITM,ITC,QOH,PRS FROM IFG WHERE QOH > 0"
query &= " AND ITM = #ITM"
By the way, since strings are immutable in vb.net, you should not build a string like that (first assigning to, then adding to) when you so clearly can avoid it because every concatenation creates a new string in memory. You can either use &, a StringBuilder, or one long string. For example, taking advantage of vb.net syntax to make a multiline string, you can change the vb.net to
Dim query = "
select ITM,ITC,QOH,PRS
FROM IFG
WHERE QOH > 0
AND ITM = #ITM"
which is [subjectively] much easier to read as a SQL query (add the proper parentheses based on your logic, of course!).
Based on your update, you need to add a parameter to the query. Here is a more or less complete example of a query with one parameter
Using con As New OleDbConnection("connection string")
Dim query = "
select ITM,ITC,QOH,PRS
FROM IFG
WHERE QOH > 0
AND ITM = #ITM"
Using cmd As New OleDbCommand(query, con)
cmd.Parameters.AddWithValue("#ITM", itmValue)
Using rdr = cmd.ExecuteReader()
For Each result In rdr.AsQueryable()
' do something with each result
Next
End Using
End Using
End Using

How to concatenate single quote in MySQL query with VB.NET parameter?

I am making a MySQL Select query using MySQLCommand object in VB.NET were I use parameters. I am facing an issue, in my where clause, I need to put the value for the criteria into single quote, I tried to use backslash ' (\') to escape the single quote, it does not work. I used double quotes as well, same issue. Can somebody help me? Is there something specific I need to do when using the MySQLCommand object in VB.NET with parameter and want my parameter value to be in single quote into a query?
Here is the Function in which I make the MySQL query:
Public Shared Function getGeographyUnits(critere As String, valeur As String) As List(Of geography_unit)
Dim conn As MySqlConnection = DBUtils.GetDBConnection()
Dim rdr As MySqlDataReader
conn.Open()
Dim cmd As MySqlCommand = New MySqlCommand("select ID,description from geography_unit where #critere = ''#valeur''", conn)
cmd.Parameters.AddWithValue("#critere", critere)
cmd.Parameters.AddWithValue("#valeur", valeur)
rdr = cmd.ExecuteReader()
Dim geography_units As New List(Of geography_unit)
While rdr.Read
Dim geography_unit As New geography_unit
Try
geography_unit.ID = CLng(rdr("Id"))
geography_unit.description = rdr("description")
Catch ex As Exception
End Try
geography_units.Add(geography_unit)
End While
rdr.Close()
conn.Close()
Return geography_units
End Function
Actually, I want the cmdText for my query to be something like this after rendering:
select ID,description from geography_unit where critere = 'valeur'
The issue comes mainly from the fact that I am using parameter, how can I solve it?
You need to fix your code with something like this. But please note a couple of things.
If the #valeur is enclosed in single quotes it is no more a parameter placeholder but a string constant and the parameter associated with the placeholder will not be used.
The connection should always enclosed in a using statement to avoid dangerous resources consuption on the server
If you want to have a variable list of field to which apply the valeur passed then you need to be absolutely sure that your user is not allowed to type the value for critere. You should provide some kind of control like combobox or dropdwonlist where the user could only choose between a prefixed set of values, then you can concatenate the critere variable to your sql command.
Public Shared Function getGeographyUnits(critere As String, valeur As String) As List(Of geography_unit)
Using conn As MySqlConnection = DBUtils.GetDBConnection()
Dim sqlText As String = "select ID,description from geography_unit"
conn.Open()
If Not String.IsNullOrEmpty(critere) Then
sqlText = sqlText & " where " & critere & " = #valeur"
End If
Dim cmd As MySqlCommand = New MySqlCommand(sqlText, conn)
cmd.Parameters.Add("#valeur", MySqlDbType.VarChar).Value = valeur
Using rdr As MySqlDataReader = cmd.ExecuteReader()
Dim geography_units As New List(Of geography_unit)
While rdr.Read
Dim geography_unit As New geography_unit
Try
geography_unit.ID = CLng(rdr("Id"))
geography_unit.description = rdr("description")
Catch ex As Exception
End Try
geography_units.Add(geography_unit)
End While
End Using
' rdr.Close() not needed when inside using
' conn.Close() not needed when inside using
Return geography_units
End Using
End Function
Also worth of note is the point in which I have used the Add method to add the parameter to the collection. The AddWithValue, while convenient, is the cause of a lot of bugs because it defines the type of the parameter looking at the argument received. This could end very badly when you pass dates or decimal numbers directly from a string.
Quite simply, as valeur is a string then your query needs to be as follows
"select ID,description from geography_unit where critere = '" & valeur & "'"
If valeur was numeric then the format should be as follows
"select ID,description from geography_unit where critere = " & valeur
Note the difference where single quotes are included within double quotes around the variable when it is a string.

Issue Comparing Access Column

Can someone please explain to me when the "size" column wont work for comparison but I can replace the ID column in my code and it works perfectly fine. Perhaps my formatting of the access database column for Size isnt correct?
I am basically just trying to see if the key and value in my dictionary match the conditions in the access database and if so to write one text, if not write another. The error I keep getting when I have size in my code is:
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll IErrorInfo.GetDescription failed with E_FAIL(0x80004005).
For Each KeyPair In dict
Dim key As String
Dim value As Integer
key = KeyPair.Key
value = KeyPair.Value
Dim sqlQry As String
sqlQry = "SELECT Item, Size FROM [Table] WHERE Item = '" & key & "'AND Size>" & value & " "
Console.WriteLine(sqlQry)
Dim topDecision As String
Dim cmd As OleDbCommand
cmd = New OleDbCommand(sqlQry, myconnection)
Dim myreader As OleDbDataReader
myreader = cmd.ExecuteReader()
If myreader.Read() Then
topDecision = "Order"
Else
topDecision = "Dont"
End If
myreader.Close()
Next
Connections and some other database objects provided by ADO.net use unmanaged code internally. They provide a .Dispose method where they release these resources. It is up to the coder to call the .Dispose method. Fortunately, .net provides Using...End Using blocks that handle this for us. Connections, commands and readers should be declared in the method where they are used so they can be properly closed and disposed.
Don't concatenate strings to build sql queries. Use parameters to avoid sql injection. We only need a single command and a single ParametersCollection. Only the values of the parameters change inside the loop.
A special note for OleDb parameters. The names of the parameters are ignored. The position of the parameter in the sql query should match the order that they are added to the ParametersCollection.
Declare KeyPair As KeyValuePair so you can access .Key and .Value properties.
I used a StringBuilder to collect the messages from your code. A StringBuilder is mutable (changeable) whereas a String is not. If I used a String the compiler would have to throw away a string and create a new one on each iteration. The garbage collector would be kept busy.
I used an interpolated string indicated by the $ before the string. It allows us to insert variables directly into the string if they are surrounded by braces { }.
If you follow this sample, be sure the text box at the end has Multiline = True.
Private Sub OPCode()
Dim sqlQry = "SELECT Item, Size FROM [Table] WHERE Item = #Key AND Size > #Value;"
Dim sb As New StringBuilder
Using cn As New OleDbConnection("Your connection string"),
cmd As New OleDbCommand(sqlQry, cn)
cmd.Parameters.Add("#Key", OleDbType.VarChar, 100)
cmd.Parameters.Add("#Value", OleDbType.Integer)
cn.Open()
For Each KeyPair As KeyValuePair(Of String, Integer) In dict
cmd.Parameters("#Key").Value = KeyPair.Key
cmd.Parameters("#Value").Value = KeyPair.Value
Dim topDecision As String
Using myreader = cmd.ExecuteReader()
If myreader.Read() Then
topDecision = "Order"
Else
topDecision = "Dont Order"
End If
End Using
sb.AppendLine($"{KeyPair.Key} - {topDecision}")
Next
End Using
TextBox1.Text = sb.ToString
End Sub

ms sql stored procedure return data without output

Hey all i am trying to find examples of getting data back from a stored procedure that has no parameters sent to it nor has any returned output parameter. Though it does display data.
How can i get that from my code im using below?
Dim myCommandSQL As New SqlCommand
Dim myReaderSQL As SqlDataReader = Nothing
Dim intX As Integer = 0
Dim connSql As SqlConnection
Try
connSql = New SqlConnection("Server=sqlprod;" & _
"Database=ISS3_PROD;" & _
"User ID=xxx;" & _
"Password=xxx;" & _
"Trusted_Connection=False;")
connSql.Open()
myCommandSQL.CommandType = CommandType.StoredProcedure
myCommandSQL.CommandText = "Select_Prod"
Dim sqlParReturn1 As System.Data.SqlClient.SqlParameter = myCommandSQL.Parameters.Add("#return_value", SqlDbType.VarChar)
sqlParReturn1.Direction = ParameterDirection.Output
myCommandSQL.ExecuteNonQuery()
MsgBox(sqlParReturn1)
connSql.Close()
myCommandSQL.Dispose()
The #return_value i just put there to see what would happen but i got nothing returned.
Any help would be great!
David
If you assign a parameter to your command, then your stored procedure should take a parameter. Furthermore, if you specify the direction as Output, then you should mark that parameter as OUTPUT in your stored procedure.
If you just want the results of a stored procedure that doesn't take any parameters, then remove all the lines that include sqlParReturn1. Also, your command isn't a "non-query" -- you are querying for data. To get it, you should do this (I also refactored your code using some better-practice techniques):
Using connSql As SqlConnection = New SqlConnection(...)
connSql.Open()
Using myCommandSQL As SqlCommand = connSql.CreateCommand()
myCommandSQL.CommandType = CommandType.StoredProcedure
myCommandSQL.CommandText = "Select_Prod"
Using reader As SqlDataReader = myCommandSQL.ExecuteReader()
If reader.HasRows Then
While reader.Read()
// loops through the rows returned
End While
End If
End Using
End Using
End Using
Here is the MSDN documentation on reading data using an ADO datareader. I think their example explains this quite well, so I have just copy and pasted the example here. Just replace your SQL setup, and then you just need to call the ExecuteReader, followed by a while loop that runs while reader.Read finds rows. Just inside the loop, you can then access your columns via reader.Get..., using ordinals or columnnames.
Private Sub HasRows(ByVal connection As SqlConnection)
Using connection
Dim command As SqlCommand = New SqlCommand( _
"SELECT CategoryID, CategoryName FROM Categories;", _
connection)
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
If reader.HasRows Then
Do While reader.Read()
Console.WriteLine(reader.GetInt32(0) _
& vbTab & reader.GetString(1))
Loop
Else
Console.WriteLine("No rows found.")
End If
reader.Close()
End Using
End Sub

Inserting variables into a query string - it won't work!

Basically i have a query string that when i hardcode in the catalogue value its fine. when I try adding it via a variable it just doesn't pick it up.
This works:
Dim WaspConnection As New SqlConnection("Data Source=JURA;Initial Catalog=WaspTrackAsset_NROI;User id=" & ConfigurationManager.AppSettings("WASPDBUserName") & ";Password='" & ConfigurationManager.AppSettings("WASPDBPassword").ToString & "';")
This doesn't:
Public Sub GetWASPAcr()
connection.Open()
Dim dt As New DataTable()
Dim username As String = HttpContext.Current.User.Identity.Name
Dim sqlCmd As New SqlCommand("SELECT WASPDatabase FROM dbo.aspnet_Users WHERE UserName = '" & username & "'", connection)
Dim sqlDa As New SqlDataAdapter(sqlCmd)
sqlDa.Fill(dt)
If dt.Rows.Count > 0 Then
For i As Integer = 0 To dt.Rows.Count - 1
If dt.Rows(i)("WASPDatabase") Is DBNull.Value Then
WASP = ""
Else
WASP = "WaspTrackAsset_" + dt.Rows(i)("WASPDatabase")
End If
Next
End If
connection.Close()
End Sub
Dim WaspConnection As New SqlConnection("Data Source=JURA;Initial Catalog=" & WASP & ";User id=" & ConfigurationManager.AppSettings("WASPDBUserName") & ";Password='" & ConfigurationManager.AppSettings("WASPDBPassword").ToString & "';")
When I debug the catalog is empty in the query string but the WASP variable holds the value "WaspTrackAsset_NROI"
Any idea's why?
Cheers,
jonesy
alt text http://www.freeimagehosting.net/uploads/ba8edc26a1.png
I can see a few problems.
You are using concatenation in a SQL statement. This is a bad practice. Use a parameterized query instead.
You are surrounding the password with single quotes. They are not needed and in fact, I'm surprised it even works assuming the password itself does not have single quotes.
You should surround classes that implement IDisposable with a Using block
You should recreate the WASP connection object in GetWASPcr like so:
Public Sub GetWASPAcr()
Dim username As String = HttpContext.Current.User.Identity.Name
Dim listOfDatabaseConnectionString As String = "..."
Using listOfDatabaseConnection As SqlConnection( listOfDatabaseConnectionString )
Using cmd As New SqlCommand("SELECT WASPDatabase FROM dbo.aspnet_Users WHERE UserName = #Username")
cmd.Parameters.AddWithValue( "#Username", username )
Dim dt As New DataTable()
Using da As New SqlDataAdapter( cmd )
da.Fill( dt )
If dt.Rows.Count = 0 Then
WaspConnection = Null
Else
Dim connString As String = String.Format("Data Source=JURA;Initial Catalog={0};User Id={1};Password={2};" _
, dt.Rows(0)("WASPDatabase") _
, ConfigurationManager.AppSettings("WASPDBUserName") _
, ConfigurationManager.AppSettings("WASPDBPassword"))
WaspConnection = New SqlConnection(connString);
End If
End Using
End Using
End Using
End Sub
In this example, listOfDatabaseConnectionString is the initial connection string to the central database where it can find the catalog name that should be used for subsequent connections.
All that said, why would you need a class level variable to hold a connection? You should make all your database calls open a connection, do a sql statement, close the connection. So, five database calls would open and close a connection five times. This sounds expensive except that .NET gives you connection pooling so when you finish with a connection and another is requested to be opened, it will pull it from the pool.
Your string passed into the constructor for this SqlConnection object will be evaluated when the class is instantiated. Your WASP variable (I'm assuming) won't be set until the method you have shown is called.
Might want to quit looking one you have found your database:
For i As Integer = 0 To dt.Rows.Count - 1
If dt.Rows(i)("WASPDatabase") Is DBNull.Value Then
WASP = ""
Else
WASP = "WaspTrackAsset_" + dt.Rows(i)("WASPDatabase")
break
End If
Next
[link text][1]You are building your string on the fly by adding the value of a column to a string. So, for the row in question for the column "WASPDatabase" was tacked on to your string. So you got what it had. On another note, your earlier query of "select ... from ... where ..." where you are manually concatinating the string of a variable makes you WIDE OPEN to SQL-Injection attacks.
Although this link [1]: how to update a table using oledb parameters? "Sample query using parameterization" is to a C# sample of querying with parameterized values, the similar principles apply to most all SQL databases.
At the time you're creating the new connection, WASP is holding the value you want it to be holding? It is a string data type? Try adding .ToString after WASP and see if that helps anything.
Interesting problem. =-)
The problem is, as Paddy already points out, that the WaspConnection object gets initialized before you even have the chance to call GetWASPAcr. Try this:
Public Sub GetWASPAcr()
'[...]
End Sub
Dim _waspConnection As SqlConnection
Public Readonly Property WaspConnection As SqlConnection
Get
If _waspConnection Is Nothing Then
GetWASPAcr()
_waspConnection = New SqlConnection("Data Source=JURA;Initial Catalog=" & WASP & ";User id=" & ConfigurationManager.AppSettings("WASPDBUserName") & ";Password='" & ConfigurationManager.AppSettings("WASPDBPassword").ToString & "';")
End If
Return _waspConnection
End Get
End Property