How to concat to access cell using vb.net - sql

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"

Related

Visual basic - Incrementing the score

Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim READER As MySqlDataReader
Dim Query As String
Dim connection As MySqlConnection
Dim COMMAND As MySqlCommand
Dim item As Object
Try
item = InputBox("What is the item?", "InputBox Test", "Type the item here.")
If item = "shoe" Then
Dim connStr As String = ""
Dim connection As New MySqlConnection(connStr)
connection.Open()
Query = "select * from table where username= '" & Login.txtusername.Text & " '"
COMMAND = New MySqlCommand(Query, connection)
READER = COMMAND.ExecuteReader
If (READER.Read() = True) Then
Query = "UPDATE table set noOfItems = noOfItems+1, week1 = 'found' where username= '" & Login.txtusername.Text & "'"
Dim noOfItems As Integer
Dim username As String
noOfItems = READER("noOfItems") + 1
username = READER("username")
MessageBox.Show(username & "- The number of items you now have is: " & noOfGeocaches)
End If
Else
MsgBox("Unlucky, Incorrect item. Please see hints. Your score still remains the same")
End If
Catch ex As Exception
MessageBox.Show("Error")
End Try
I finally got the message box to display! but now my code does not increment in the database, can anybody help me please :D
Thanks in advance
After fixing your typos (space after the login textbox and name of the field retrieved) you are still missing to execute the sql text that updates the database.
Your code could be simplified understanding that an UPDATE query has no effect if the WHERE condition doesn't find anything to update. Moreover keeping an MySqlDataReader open while you try to execute a MySqlCommand will trigger an error in MySql NET connector. (Not possible to use a connection in use by a datareader). We could try to execute both statements in a single call to ExecuteReader separating each command with a semicolon and, of course, using a parameter and not a string concatenation
' Prepare the string for both commands to execute
Query = "UPDATE table set noOfItems = noOfItems+1, " & _
"week1 = 'found' where username= #name; " & _
"SELECT noOfItems FROM table WHERE username = #name"
' You already know the username, don't you?
Dim username = Login.txtusername.Text
' Create the connection and the command inside a using block to
' facilitate closing and disposing of these objects.. exceptions included
Using connection = New MySqlConnection(connStr)
Using COMMAND = New MySqlCommand(Query, connection)
connection.Open()
' Set the parameter value required by both commands.
COMMAND.Parameters.Add("#name", MySqlDbType.VarChar).Value = username
' Again create the reader in a using block
Using READER = COMMAND.ExecuteReader
If READER.Read() Then
Dim noOfItems As Integer
noOfItems = READER("noOfItems")
MessageBox.Show(username & "- The number of items you now have is: " & noOfItems )
End If
End Using
End Using
End Using

Receiving an error when attempting to update a record

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.

OledbException Data type mismatch in criteria expression

I'm getting a OledbException Data type mismatch in the criteria expression, at ad.Fill(xDataset, "TblMaster").
I'm using an Access database and Telerik Reporting.
This is my code
Public Sub TanggalX()
conn.Open()
Dim str9 As String = "Select * From TblMaster Where Tanggal='" & Me.DateTimePicker1.Value.Date.ToString("yyyy/MM/dd")) & "'"
ad = New OleDb.OleDbDataAdapter(str9, conn)
xDataset.Clear()
ad.Fill(xDataset, "TblMaster")
obj_RepDoc = New Report1
obj_RepDoc.DataSource = (xDataset)
Me.ReportViewer1.Report = obj_RepDoc
Me.ReportViewer1.RefreshReport()
Me.Show()
conn.Close()
End Sub
Please help me this is my last problem for this project.
You should use # instead of ' for Date/Time fields.
Dim str9 As String = "SELECT * FROM TblMaster WHERE Tanggal=#" & Me.DateTimePicker1.Value.Date.ToString("yyyy/MM/dd")) & "#"
My guess is that TblMaster.Tangall is of type Date and you are specifying it as a string in the WHERE clause of your SQL select command.
Try the following:
using (OleDbCommand comm = new OleDbCommand())
{
var parameter =comm.Parameters.AddWithValue("#tangall", Me.DateTimePicker1.Value);
parameter.OleDbType = OleDbType.DBDate;
using (var ad = new OleDbDataAdapter(comm))
{
... //do your stuff here
}
}
I think InBetween is right. You can also convert the string to date inside the SQL statement instead of using parameters by replacing your SQL statement with this:
Dim str9 As String = "Select * From TblMaster Where Tanggal=CDate('" & Me.DateTimePicker1.Value.ToString() & "')"

ORA-01704: string literal too long when updating a record

I am trying to update an Oracle Database record and i keep getting this error:
ORA-01704: string literal too long 5
I looked up that error and it seems that i have a limit of 4000 charters since i am using Oracle 10g. However, the prgblem is that its the same exact data i am putting back into that record so that is why i am unsure as to why its giving me that error for the same amount of data i took out of it.
Here is my update code:
Dim myCommand As New OracleCommand()
Dim ra As Integer
Try
myCommand = New OracleCommand("Update CSR.CSR_EAI_SOURCE Set STATUS_CODE = 'Blah', COMPLETE_DATE = '', DATA = '" & theData & "' WHERE EID = '81062144'", OracleConnection)
ra = myCommand.ExecuteNonQuery()
OracleConnection.Close()
Catch
MsgBox("ERROR" & Err.Description & " " & Err.Number)
End Try
I'm not sure if there is anything special you have to do in order to update a clob or not.
I extract the clob like so:
Dim blob As OracleClob = dr.GetOracleClob(9)
Dim theData As String = ""
theData = blob.Value
And it works just fine extracting but just not putting it back in.
Any help would be great!
David
UPDATE CODE
Dim OracleCommand As New OracleCommand()
Dim myCommand As New OracleCommand()
Dim ra As Integer
While dr.Read()
Dim blob As OracleClob = dr.GetOracleClob(9)
Dim theData As String = ""
theData = blob.Value
theData = Replace(theData, "…", " ")
Try
Dim strSQL As String
isConnected2 = connectToOracleDB2()
OracleConnection.Close()
If isConnected2 = False Then
MsgBox("ERRORConn: " & Err.Description & " " & Err.Number)
Else
myCommand.Connection = OracleConnection2
strSQL = "Update CSR.CSR_EAI_SOURCE Set STATUS_CODE = 'ERROR', COMPLETE_DATE = '', DATA = :1 WHERE EID = '" & theEID & "'"
myCommand.CommandText = strSQL
Dim param As OracleParameter = myCommand.Parameters.Add("", OracleDbType.Clob)
param.Direction = ParameterDirection.Input
param.Value = theData
Application.DoEvents()
ra = myCommand.ExecuteNonQuery()
Application.DoEvents()
OracleConnection2.Close()
Application.DoEvents()
End If
Catch
MsgBox("ERROR: " & Err.Description & " " & Err.Number)
OracleConnection2.Close()
End Try
End While
dr.Close()
OracleConnection.Close()
Do not hardcode the value into your SQL query. Instead wrap it in a parameter. Like this:
Dim strSQL As String
strSQL = "Update CSR.CSR_EAI_SOURCE Set STATUS_CODE = 'Blah', COMPLETE_DATE = '', DATA = :1 WHERE EID = '81062144'"
myCommand.CommandText=strSQL
And then:
Dim param As OracleParameter=myCommand.Parameters.Add("",OracleDbType.Clob)
param.Direction=ParameterDirection.Input
param.Value=blob.Value
You can (and should) of course add all other variables (status code, complete date, eid) of your query as parameters, too, instead of hard-coding them into your SQL.
Varchar2 in sql has a limitations of 4000 characters. This limitation does not apply to the data stored in a varchar column. You need to convert this to pl\sql or specify some other column type. ( I am not a php expert. So I cannot provide any sample, just the reason for your error).
Essentially you need to specify the data type as clob while executing the bind query. Otherwise it will default to varchar2 and the above limitation will apply.

Selecting an integer from an Access Database using SQL

Trying to select an integer from an Access Database using an SQL statement in VB
Dim cmdAutoTypes As New OleDbCommand
Dim AutoTypesReader As OleDbDataReader
cmdAutoTypes.CommandText = "SELECT * FROM AutoTypes WHERE TypeId = '" & cboTypeIds.Text & "'"
AutoTypesReader = cmdAutoTypes.ExecuteReader
Error message says: "OleDbException was unhandled: Data type mismatch in criteria expression." and points to the AutoTypesReader = cmdAutoTypes.ExecuteReader line
Rather make use of OleDbParameter Class
This will also avoid Sql Injection.
You don't need the quotes in the query string. You're searching for a number, not a string.
cmdAutoTypes.CommandText = "SELECT * FROM AutoTypes WHERE TypeId = " & cboTypeIds.Text
Hi In access SQL you can't use single quote around your Integer type.
so
command text will be.. "SELECT * FROM AutoTypes WHERE TypeId = " & cboTypeIds.Text & " and .... "
In Access SQL, don't quote numeric constants.
And test whether IsNull(cboTypeIds). You can't do what you were planning to do until a value has been chosen.
Do not use string concatenation when you build your SQL query, use parameters instead.
Dim cmd As OledbCommand = Nothing
Dim reader as OleDbDataReader = Nothing
Try
Dim query As String = "SELECT * FROM AutoTypes WHERE TypeId = #Id"
cmd = New OledbCommand(query, connection)
//adding parameter implicitly
cmd.Parameters.AddWithValue("#Id", cboTypeIds.Text)
reader = cmd.ExecuteReader()
Catch ex As Exception
Messagebox.Show(ex.Message, MsgBoxStyle.Critical)
End Try
You can also explicitly state the parameter data type.
cmd.Parameters.Add("#Id", OleDbType.Integer).Value = cboTypeIds.Text
Hope this helps.