Sql in Visual Basic returning nothing while same query in Access returns right value - sql

My code:
strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=PIZZA.accdb"
strSql = "SELECT INGREDIENTNR AS NR FROM INGREDIENTS WHERE DESCRIPTION = '" & ingredients(counter * 2) & "'"
objConnection = New OleDbConnection(strConnectionString)
objCommand = New OleDbCommand(strSql, objConnection)
objConnection.Open()
objDataReader = objCommand.ExecuteReader(CommandBehavior.CloseConnection)
Dim strIngNr As String = objDataReader("NR")
Dim strIngNr As String = objDataReader("NR") gives the error: No data exists for the row/column.
But the same query in Access does return 14, which is the right value and what I want to get. What am I doing wrong?
Another thing: counter is the right value, tested that already.
And another thing: DESCRIPTION is a String

Related

Getting value for webpage - rewriting code so no sql injection

I'm trying to rewrite my code to prevent vulnerability to SQL Injection. I see code for inserting or updating tables, but not for just getting a value. Here is the code I have that is vulnerable:
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
'Get employeeid from table that matches login name
cmde.CommandText = "SELECT EmployeeID FROM tblEmployees where login = '" & vname & "'"
cmde.CommandType = CommandType.Text
cmde.Connection = sqlConnection
sqlConnection.Open()
'employeeid
rve = cmde.ExecuteScalar()
sqlConnection.Close()
I started rewriting the code and this is what I have so far:
sql1 = "Select EmployeeID from tblEmployees where login = #loginname"
cmde = new sqlcommand(sql1)
This is where I'm stuck:
cmde.parameters.????("#loginname", vname)
cmde.ExecuteReader()
I'm not adding or updating or inserting - I just want the value to appear on my webpage. What is the code for this? And is the rest of the code correct? Thanks in advance!
****Continued...
After help, I came up with this code but I'm getting an error - ExecuteReader: Connection property has not been initialized. I'm confused. Here's the code:
Dim windowsLoginName As System.String = HttpContext.Current.User.Identity.Name 'System.Security.Principal.WindowsIdentity.GetCurrent().Name
Dim split As String() = Nothing
Dim vname As String
Dim sqlConnection As New SqlConnection("Data Source=WillSQL\ict2;Initial Catalog=TimeSQL;Integrated Security=SSPI")
Dim sqlemp As String
Dim cmde As New SqlCommand
Dim rve As Object
'Get network login name (name only)
split = windowsLoginName.Split("\".ToCharArray)
vname = split(1)
'Get employeeid from table that matches login name
sqlConnection.Open()
sqlemp = "SELECT EmployeeID FROM tblEmployees where login = #loginname"
cmde = New SqlCommand(sqlemp)
cmde.Parameters.AddWithValue("#loginname", vname)
rve = cmde.ExecuteReader()
sqlConnection.Close()

How to concat to access cell using vb.net

I want to concat(add to what already exist) to an access cell using the text from a vb.net textbox. I tried using UPDATE but I'm getting a syntax error. This is what I tried so far
Dim ds As New DataSet()
Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\equip_full.mdb;Jet OLEDB:Database Password=matt"
Dim db As String = "Update INTO Equipment set TypeItem = ISNULL(TypeItem, '') & #EquipmentItem WHERE EquipmentCat = #category"
Using cn As New OleDbConnection(ConnectionString)
Using cmd = New OleDbCommand(db, cn)
cn.Open()
cmd.Parameters.Add("#EquipmentItem", OleDbType.VarWChar).Value = Form4.TextBox1.Text & ";"
cmd.Parameters.Add("#category", OleDbType.VarWChar).Value = Me.item_text.Text
Using reader = cmd.ExecuteReader()
'some code...
End Using
End Using
End Using
The correct syntax for an Update query is
UPDATE tablename SET field=value, field1=value1,.... WHERE condition
Then you need to remove that INTO that is used in the INSERT queries
Dim db As String = "Update Equipment set TypeItem = .... " &
"WHERE EquipmentCat = #category"
After fixing this first syntax error, then you have another problem with ISNull
ISNull is a boolean expression that return true or false.
If you want to replace the null value with an empty string you need the help of the IIF function that you could use to test the return value of ISNull and prepare the base string to which you concatenate the #Equipment parameter.
Something like this
Dim db As String = "Update Equipment " & _
"set TypeItem = IIF(ISNULL(TypeItem),'', TypeItem) & #EquipmentItem " & _
"WHERE EquipmentCat = #category"

How to update data in table datagridview in vb.net

i used this coding for my update button to update data in my table in datagridview but it is still shows error. i need some help to solve this problem
Dim MyItems As Integer
Dim MyItemNo As Integer
Dim ItemDescription As String
MyItems = GridViewItems.CurrentRow.Index
MyItemNo = GridViewItems.Item(0, MyItems).Value
ItemDescription = GridViewItems.Item(1, MyItems).Value
Dim SqlQuery As String = " UPDATE ITEMS = '" & MyItems & "'WHERE Item_No = " & MyItemNo & ""
Dim SqlCommand As OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
Your use of the UPDATE sql statement is wrong. The correct syntax is
UPDATE <tablename> SET <field1> = <value>, <field2> = <value> WHERE <field3> = <value>
but there is also the problem of string concatenation that should be addressed.
So you could rewrite your code as
Dim SqlQuery As String = "UPDATE yourTableName SET ITEMS = ? WHERE Item_No = ?"
Dim SqlCommand As OleDbCommand
With SqlCommand
.CommandText = SqlQuery
.Connection = conn
.Parameters.AddWithValue("#p1", MyItems)
.Parameters.AddWithValue("#p2", MyItemNo)
.ExecuteNonQuery()
End With
This is an example of a parameterized query. You should always use this approach when you need to pass values submitted by your user to your database. Without this your code is open to SQL Injection and other parsing problems

I can not read from database Visual basic

Dim conStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\databaseVB\bakery.accdb"
Dim conn As New OleDbConnection(conStr)
Dim cmd As New OleDbCommand
Dim reader As OleDbDataReader
Dim Item(5) As String
Dim key = TextBox1.Text
conn.Open()
cmd.Connection = conn
1>>>>> 'cmd.CommandText = "SELECT * FROM Member WHERE number = 3"
2>>>>> cmd.CommandText = "SELECT * FROM Member WHERE number = '" & key & "'"
MessageBox.Show(cmd.CommandText)
reader = cmd.ExecuteReader()
While reader.Read
Item(0) = reader("Number").ToString
Item(1) = reader("FirstName").ToString
Item(2) = reader("LastName").ToString
Item(3) = reader("User").ToString
Item(4) = reader("Pass").ToString
End While
MessageBox.Show(Item(1).ToString)
conn.Close()
from 1>>> I can read Item in databaes
from 2>>> I can not read Item
Try using a parameterized query string:
cmd.CommandText = "SELECT * FROM Member WHERE number = #Number"
After this add your parameters.
//cmd.Parameters.Add("#Number", SqlDbType.Int).Value = 3;
//It is better to use .TryParse(), incase your users write non numerical values in the Textbox
cmd.Parameters.Add("#Number", SqlDbType.Int).Value = (int)TextBox1.Text;
Additionally you need to watch your data types. 3 is of type int, but TextBox1.Text is of type string. You need to parse the string to int in order for it to work.
This should do the trick and prevent ugly syntax juggling, while mixing strings and variables; And prevent you from SQL Injection attacks.

Deleting-Updating a dataview

I need your help PLEASE!
I have a table: tblCustomer. (serial,Name,Email,Address)
I did the following:
insert-update-delete in dataset(that contains the table tblCustomer)
What I need to do, and I need your help in it, is:
insert-update-delete in dataview.
I tried to do the following:
Dim dv As New DataView(_DataSet.Tables(0))
' select deleted rows
dv.RowStateFilter = DataViewRowState.Deleted
For _irow As Long = 0 To dv.Table.Rows.Count - 1
' if serial is null, that means the row is new and deleted
' so no need to add it to database
If Not IsDBNull(dv!serial) Then
' delete row from database
Dim _SQL As String = "DELETE FROM tblCustomer WHERE Serial = " & dv!serial.ToString
' open the connection and execute the delete command
Dim strconnection As String = "Data Source=EASMAR-PC;Initial Catalog=Database Connection;Integrated Security=True;"
Dim _cn As SqlConnection = New SqlConnection(strconnection)
_cn.Open()
Dim cmd As New SqlCommand
cmd.CommandText = "Delete from tblCustomer where serial= '" & txtSerial.Text & "'"
End If
Next
I am getting this error: Conversion from string "serial" to type 'Integer' is not valid.
On this line: If Not IsDBNull(dv!serial) Then
And the same error on: Dim _SQL As String = "DELETE FROM tblCustomer WHERE Serial = " & dv!serial.ToString
Can you help me PLEASE.
Thank you.
what type is serial? Integer I guess, from the error. Plus it seems you're passing the literal string value "serial" instead of a number.
Also, in your two DELETE statements you're passing it both WITH and WITHOUT ' '.
remove those ' '.
And what's that _SQL string variable? you're not using it.
Try:
If Not IsDBNull(dv!serial) Then
' open the connection and execute the delete command
Dim strconnection As String = "Data Source=EASMAR-PC;Initial Catalog=Database Connection;Integrated Security=True;"
Dim _cn As SqlConnection = New SqlConnection(strconnection)
_cn.Open()
Dim cmd As New SqlCommand
cmd.CommandText = "Delete from tblCustomer where serial= " & txtSerial.Text
End If