Updating MySQL record not working using parameters - mysql

Good day, I'm having a problem updating records in MySQL. The following code is in VB.Net. Whenever I execute the code I get no errors, but the information is not saved in the table. Please tell me what I am doing wrong.
SQLstr = "UPDATE mainfinancials SET charge1=?charge1, charge2=?charge2, charge3=?charge3, charge4=?charge4, charge5=?charge5" _
& " WHERE acct='?acct';"
Pcomm.CommandText = SQLstr
If IsNumeric(txtCharge1.Text) Then Pcomm.Parameters.AddWithValue("?charge1", CDbl(txtCharge1.Text))
If IsNumeric(txtCharge2.Text) Then Pcomm.Parameters.AddWithValue("?charge2", CDbl(txtCharge2.Text))
If IsNumeric(txtCharge3.Text) Then Pcomm.Parameters.AddWithValue("?charge3", CDbl(txtCharge3.Text))
If IsNumeric(txtCharge4.Text) Then Pcomm.Parameters.AddWithValue("?charge4", CDbl(txtCharge4.Text))
If IsNumeric(txtCharge5.Text) Then Pcomm.Parameters.AddWithValue("?charge5", CDbl(txtCharge5.Text))
Pcomm.Parameters.AddWithValue("?acct", txtAcct.Text)
MsgBox(SQLstr)
Try
PConn.Open()
Pcomm.ExecuteNonQuery()
PConn.Close()
PConn.Dispose()
Catch ex As MySqlException
MsgBox(ex.Message.ToString())
PConn.Close()
End Try
I have deliberately place error in the the code and it would return an error message.
can some one help me with this.
Thanks

Do not enclose a parameter placeholder with single quotes
" WHERE acct=?acct;"
Enclosing the parameter placeholder in single quotes trasform its name in a literal value. So you query is searching a record where the acct column contains the literal value '?acct'.
Of course it finds nothing and nothing is updated
By the way, once a parameter placeholder is present in the query string, you should supply a parameter for it. If you forget to add the parameter an error occurs when you execute the command stating that an expected parameter is missing.
You place a test for IsNumeric and only if it succeds you add the parameter. I think you should test this error condition before and abort the update if something is not correct in your charge parameters.

Related

I'm having difficulties in manipulating records from MySQL database

I'm having difficulties in retrieving and displaying records from a table in a database. I'm using a MySql database and VB.NET 2012.
I'm getting the following error message
"End of statement expected"
Remove the space between Form2 and _Load. Your SQL statement is also broken, the AND being in blue shows this. You have your single and double quotes confusing it, the statement is being ended before the AND due to incorrect syntax. In any case, you should, probably, be using
"SELECT * FROM bigregdb WHERE regID = '"1"' OR regID = '"2"'"

Access Query - correct Format for a statement in the MS Access query

I have VBA codes in Access Database. I'm getting an error message "Run Time Error 3464 - Data Type Mismatch in Expression" with the following lines in my codes. What is the correct format of this line? I'm sure its a simple quotation mark or something missing from the line.
Within the Database, there is column called APIC Members. I want only the Records that have "1" listed in the cells.
Table$ = "SELECT * From WHY_Open_Cases_YTD WHERE WHY_Open_Cases_YTD.[APIC Member] = 1;"
Set RST = myDB.OpenRecordset(Table$)
Please advise what I'm doing wrong. When I Debug the message, I get the Set RST = myDB.OpenRecordset (Table$) is highlighted.
On my Access 2003 and 2007 systems, the complete description for error #3464 is "Data type mismatch in criteria expression." The db engine is complaining about the SQL statement you're asking it to use.
If [APIC Member] is text data type instead of numeric data type, add quotes around the value you compare against.
Table$ = "SELECT * From WHY_Open_Cases_YTD WHERE [APIC Member] = '1';"
"Data Type Mismatch" sounds to me as if you are opening the wrong type of Recordset.
myDB.OpenRecordset() expects a DAO.Recordset, and your RST is probably an ADODB.Recordset.
See this answer for a more in-depth explanation:
Open recordset in Access 2003/2007
Try
Table$ = "SELECT * From WHY_Open_Cases_YTD WHERE '[APIC Member]' = '1';"
I had same issue with DAO, and it turns out that it will not accept the SQL query until you have quoted the field name as well.

error code 3021 either bof or eof is true or the current record has been deleted

I have an Access 2003 database with some visual basic code using ADO calls in it. When I do a
strsql0 = "SELECT lnk_stockitm.C_C FROM lnk_stockitm WHERE (((lnk_stockitm.C_C) Like 'T*'));"
newRS.Open strsql0, cn1, adOpenKeyset, adLockReadOnly
newRS.movelast
I get this error:
3021 either bof or eof is true or the current record has been deleted
When I run the exact same query in the same function without the WHERE clause, like this:
strsql0 = "SELECT lnk_stockitm.C_C FROM lnk_stockitm;
I get the correct result of 56,000 records. If I paste the full SQL statement with the WHERE clause into a regular query, like so:
SELECT lnk_stockitm.C_C FROM lnk_stockitm WHERE (((lnk_stockitm.C_C) Like 'T*'));
it returns the correct subset of the results (2800 records).
Can anyone tell me what I am doing wrong?
The wildcard difference is the cause for difference between what you execute from ADO and within your access database. Convert your statement to use "%" rather than "*". As a general rule of thumb, it may be a good idea to encapsulate your code by checking for eof before calling MoveLast. If your query has zero results it'll bomb out every time.
strsql0 = "SELECT lnk_stockitm.C_C FROM lnk_stockitm WHERE (((lnk_stockitm.C_C) Like 'T*'));"
newRS.Open strsql0, cn1, adOpenKeyset, adLockReadOnly
if not newRs.eof then
newRS.movelast
else
' do something here if necessary to handle blank results
end if
You need to use the '%' character as wildcard when using ADO.
MSDN Article: Using the Right Wildcard Characters in SQL Statements

Getting "final" prepared statement from MySqlCommand

I have the following MySqlCommand:
Dim cmd As New MySqlCommand
cmd.CommandText = "REPLACE INTO `customer` VALUES( ?customerID, ?firstName, ?lastName)"
With cmd.Parameters
.AddWithValue("?customerID", m_CustomerID)
.AddWithValue("?firstName", m_FirstName)
.AddWithValue("?lastName", m_LastName)
End With
I have a class that handles execution of MySqlCommands and I'd like to have it log every query to a file. I can retrieve the query/command being executed with:
cmd.CommandText
but that just returns the original CommandText with the parameters (?customerID, ?firstName, etc.) and not the actual substituted values added by the AddWithValue functions. How can I find out the actual "final" query that was executed?
I did the following:
dim tmpstring as string = MySqlCommand.CommandText
For each p as MySqlParameter in MySqlCommand.parameters
tmpstring = tmpstring.replace(p.ParameterName, p.Value)
Next
This seems to output everything you need
I havn't seen a method for this.
And in any case, prepared statements are sent to the server with the ?customerID,?firstname parameters, and then the actual parameters are sent seperately - the mysql driver doesn't build up a final sql query like you'd do if you didn't use prepared statements.
The parameterised method you're using should be okay for preventing SQL injection.
.AddWithValue("?customerID", m_CustomerID)
If m_CustomerID contains the text
Haha I'm stealing your data; drop table whatever;
Then it won't end up being executed on the server as such. The AddWithValue sorts that out for you.
As for the actual executed query, you should be able to get that from the query-log, if it's enabled.
You would have to build it yourself.
Parameters are not just plopped into a string and then run as a SQL statement. The RDBMS will actually prepare the SQL and then use the parameter values as needed. Therefore, there's not a single SQL statement going to the server. To see what the SQL would be, you would have to do:
Console.WriteLine("REPLACE INTO `customer` VALUES('" & m_CustomerID & _
"', '" & m_FirstName & "', '" & m_LastName & "')")
I have the same need.
From what I've read, the query text isn't combined with the param values in the client - they are sent to the server for that.
To inspect what query was actually being sent to the server, I used mysqld logging. For my version of MySQL, I added this entry to the my.cnf:
log=queries.txt
Then, I was able to see clearly the effect of combining command text with parameters: in my case, after restarting the mysqld, I ran my unit tests and then opened the queries.txt file.
HTH!
If you want to manage logging yourself from the .NET application, your best bet is to continue using the MySqlCommand class with parameters to avoid SQL injection; however, when you log the CommandText, loop through the Parameters collection and log each one by name/type/value.

myString = "UPDATE " results in an empty myString

In MS Access assigning a string literal will sometimes result in an empty String
The following code
Public Sub test()
Dim myString As String
myString = "UPDATE "
Debug.Print "'" & myString & "'"
End Sub
results in
''
this is freaking me out. It only happens sometimes. Other times the "UPDATE " will work, but myString = "tblCategorie" won't. It needs to be exactly that String. If "UPDATE " fails, then "update " will still be okay.
I'm using MS Access 2003 11.8204.8221 SP3 Does anyone have the same problem?
(before you say: dump access! we're already doing that, but still in a transitional phase. I'm not really expecting anyone to come up with a decent answer, but a guy can hope)
[UPDATE]: Thanks for all the comments! let me just put really clear though that
it's not a typo. The same code sometimes works, and sometimes doesn't.
It's run in isolation so it's no global variable problem.
I have updated the sample to be the exact code that fails/doesn't fail. It's a literal copy. I test it by pasting it in a module and typing 'test' in the direct screen.
It first popped up in code that had worked flawlessly the past half year,
It is really the string assignment that fails (I can check that by putting a break on the assignment statement)
I generate my database from text exports, so it can't really be a corruption problem. (It could be, but it's not one that I can fix by compressing etc.)
Are you using On Error Resume Next i.e. is the assignment failing silently? That said, I can't think why an assignment of a String literal to a String variable would fail, which begs the question: is mySting really typed as String?
UPDATE: I see from your UPDATE (pun intended?) that my guesses are off. I simply cannot see how your code could fail to print anything other than 'UPDATE '. Perhaps you should now view this as an opportunity to abandon dynamic SQL in favour of prepared statements or, preferably, PROCEDURES (sure, in ACE/Jet's stored procs are limited to a single SQL statement but at least they keep the SQL code in the correct place i.e. the db).
Is the code you posted a copy of the code that is failing, or a reasonable facimile? I'm wondering if someting was lost in paraphrasing, as I don't see anything at all wrong with the code you posted.
Just a blind guess... are you sure you are typing the second "myString" correctly?
Beacuse il you don't (ex.
Debug.print "'" & mySting & "'"
) Access won't complain but it will create an empty variable...
Dump access! :-)
Something is FUBAR.Have you tried a Compact and Repair on the database?
The other thing I would try is to run a copile on the VBA code (Debug->Compile Access[X]).