Receiving an error when attempting to update a record - sql

In my program I have a function titled runSQL, here it is:
Dim Connection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=TrainingLog.accdb")
Dim DT As New DataTable
Dim DataAdapter As OleDb.OleDbDataAdapter
Connection.Open()
DataAdapter = New OleDb.OleDbDataAdapter(query, Connection)
DT.Clear()
DataAdapter.Fill(DT)
Connection.Close()
Return DT
And I'm trying to update a record in a database using the update string, sourced from this code:
Dim sqlString As String
sqlString = "UPDATE UserRecords set FirstName = '" & txtName.Text
sqlString = sqlString & "', LastName = '" & txtSurname.Text
If ChkSmoker.Checked = True Then
sqlString = sqlString & "', Smoker = true"
ElseIf ChkSmoker.Checked = False Then
sqlString = sqlString & "', Smoker = false"
End If
sqlString = sqlString & ", Weight = " & txtWeight.Text
If RdoMale.Checked = True Then
sqlString = sqlString & ", Gender = 'm'"
ElseIf RdoFemale.Checked = True Then
sqlString = sqlString & ", Gender = 'f'"
End If
sqlString = sqlString & " WHERE UserName = '" & LstUsers.SelectedItem.ToString & "'"
runSQL(sqlString)
However once I click the save button, I get an error from line 7 of the runSQL function (not including empty line, so that's the DataAdapter.Fill(DT) line) which says "No value given for one or more required parameters."
I wondered if anyone knew why this is or how to fix it.
One thing I did think of is that, in the table being updated, there are fields other than those being mentioned in my UPDATE statement. For example there is a Yes/no field titled "TeamMember", which I don't mention in the update statement.
When using the update function, do I have to give values for every field, even those not being changed?
Thanks for reading, and hopefully helping!

You should never composea SQL query yourself. It much easies and safer (to vaoid SQL injection) to create a parameterized query, or use an stored procedure. And then execute it by pasing the query or stored procedure name and the parameter values.
Besides, in this way, you don't have to take care of what the right format is for a particular value. For example, how do you format a date? And, how do you format a boolean value? Most probably the problem with your query is the false or true value that you're trying to set for the Smoker column, because in TSQL that's a bit value, and can only be 0 or 1.
Check this to see samples of using parameters: ADO.NET Code Examples (Click the VB tab to see it in VB). You'll see that you define a parameter specifying a name with an # prefix in the query, and then you simply pass a value for each parameter in the query, and it will be passed to the server in the correct format without you taking care of it.
Taken from one of the samples:
Dim queryString As String = _
"SELECT ProductID, UnitPrice, ProductName from dbo.Products " _
& "WHERE UnitPrice > #pricePoint " _
& "ORDER BY UnitPrice DESC;"
Dim command As New SqlCommand(queryString, connection)
command.Parameters.AddWithValue("#pricePoint", paramValue)
'' command.ExecuteXXX
NOTE that you can execute the command in different ways, depending on your need to simply execute it or get an scalar value or a full dataset as a result.

Related

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

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 check duplicate record before insert, using vb.net and sql?

can someone help me with my code, i need to check first if record exist. Well i actually passed that one, but when it comes to inserting new record. im getting the error "There is already an open DataReader associated with this Command which must be closed first." can some help me with this? thanks.
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim reg_con As SqlConnection
Dim reg_cmd, chk_cmd As SqlCommand
Dim checker As SqlDataReader
Dim ID As Integer
Dim fname_, mname_, lname_, gender_, emailadd_, college_, password_ As String
ID = idnumber.Value
fname_ = fname.Value.ToString
mname_ = mname.Value.ToString
lname_ = lname.Value.ToString
gender_ = gender.Value.ToString
college_ = college.Value.ToString
emailadd_ = emailadd.Value.ToString
password_ = reg_password.Value.ToString
reg_con = New SqlConnection("Data Source=JOSH_FLYHEIGHT;Initial Catalog=QceandCceEvaluationSystemDatabase;Integrated Security=True")
reg_con.Open()
chk_cmd = New SqlCommand("SELECT IDnumber FROM UsersInfo WHERE IDnumber = '" & ID & "'", reg_con)
checker = chk_cmd.ExecuteReader(CommandBehavior.CloseConnection)
If checker.HasRows Then
MsgBox("Useralreadyexist")
Else
reg_cmd = New SqlCommand("INSERT INTO UsersInfo([IDnumber], [Fname], [Mname], [Lname], [Gender], [Emailadd], [College], [Password]) VALUES ('" & ID & "', '" & fname_ & "', '" & mname_ & "', '" & lname_ & "', '" & gender_ & "', '" & emailadd_ & "', '" & college_ & "', '" & password_ & "')", reg_con)
reg_cmd.ExecuteNonQuery()
End If
reg_con.Close()
End Sub
Add this string to your connection string
...MultipleActiveResultSets=True;";
Starting from Sql Server version 2005, this string allows an application to maintain multiple active statements on a single connection. Without it, until you close the SqlDataReader you cannot emit another command on the same connection used by the reader.
Apart from that, you insert statement is very dangerous because you use string concatenation. This is a well known code weakness that could result in an easy Sql Injection vulnerability
You should use a parameterized query (both for the insert and for the record check)
reg_cmd = New SqlCommand("INSERT INTO UsersInfo([IDnumber], ......) VALUES (" & _
"#id, ......)", reg_con)
reg_cmd.Parameters.AddWithValue("#id", ID)
.... add the other parameters required by the other field to insert.....
reg_cmd.ExecuteNonQuery()
In a parameterized query, you don't attach the user input to your sql command. Instead you put placeholders where the value should be placed (#id), then, before executing the query, you add, one by one, the parameters with the same name of the placeholder and its corresponding value.
You need to close your reader using checker.Close() as soon as you're done using it.
Quick and dirty solution - issue checker.Close() as a first command of both IF and ELSE block.
But (better) you don't need a full blown data reader to check for record existence. Instead you can do something like this:
chk_cmd = New SqlCommand("SELECT TOP (1) 1 FROM UsersInfo WHERE IDnumber = '" & ID & "'", reg_con)
Dim iExist as Integer = chk_cmd.ExecuteScalar()
If iExist = 1 Then
....
This approach uses ExecuteScalar method that returns a single value and doesn't tie the connection.
Side note: Instead of adding parameters like you do now - directly to the SQL String, a much better (and safer) approach is to use parametrized queries. Using this approach can save you a lot of pain in the future.

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.

VB.NET: convert text with single quote to upload to Oralce DB

I have a function in VB.NET that runs a query from an MS SQL DB, puts the results into temporary variables, then updates an Oracle DB. My question is, if the string in the MS SQL contains a single quote ( ' ), how do I update the Oracle DB for something that has that single quote?
For example: Jim's request
Will produce the following error: ORA-01756: quoted string not properly terminated
The ueio_tmpALM_Comments (coming from MS SQL) is the culprit that may or may not contain the single quote.
update_oracle =
"update Schema.Table set ISSUE_ADDED_TO_ALM = '1'," & _
"ISSUE_COMMENTS = '" & ueio_tmpALM_Comments & "'," & _
"where ISSUE_SUMMARY = '" & ueio_tmpALM_Summary & "' "
Dim or_cmd_2 = New NetOracle.OracleCommand(update_oracle, OracleConn)
or_cmd_2.ExecuteNonQuery()
From your question it's clear that you are building the update query using string concatenation.
Something like this
Dim myStringVar as string = "Jim's request"
Dim sqlText as String = "UPDATE MYTABLE SET MYNAME = '" + myStringVar + "' WHERE ID = 1"
this is a cardinal sin in the SQL world. Your code will fail for the single quote problem, but the most important thing is that this code is subject to Sql Injection Attacks.
You should change to something like this
Dim cmd As OraclCommand = new OracleCommand()
cmd.Connection = GetConnection()
cmd.CommandText = "UPDATE MYTABLE SET MYNAME = :myName WHERE ID = 1"
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue(":myName", myStringVar)
cmd.ExecuteNonQuery()