VB.NET MYSQL Displaying Data using MySQL Error - mysql

Hello I'm trying to display data in vb.net using MySQL syntax here is my Mysql syntax
SELECT COUNT(status) as 'Number of Grade School for the Month of January'
FROM blhtraining.userinfo
Where survey_at='Talisay'
and status='College' and Month(member_since)='1' and
Year(member_since)='2021'
And this code works in Mysql but when i modify it like this in vb.net
Dim count_gradeSchool1 As String = "Select Case COUNT(status) As 'Members'
From training.userinfo
Where survey_at='" & txtmonthlylocation.Text & "'
And status ='College'
And Month(member_since)='" & monthly_reports & "'
And YEAR(member_since)='" & txtmyear.Text & "'
And Day(member_since)='11'"
da = New MySqlDataAdapter(count_gradeSchool1, mycon)
dt = New DataTable()
da.Fill(dt)
lblgs1.Text = dt.Rows(0)("Members")
I recieved this error
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'As 'Members'
From training.u' at line 1
I'm sure the syntax is correct is it the variable declared?

Your problems probably came about because you pasted the SQL into your code without starting a string first, so VB saw "select" and helped you out by adding "case". So, here is code that...
...has fixed SQL syntax
...uses parameters. Always use parameters. You've no idea how many times a day I say this, trying to stem the tide of future SQL injection hacks. Writing code that doesn't use parameters will get you fired, or you'll have to live with the consequences of writing hack prone code on your conscience. Don't ever skip on using parameters in your SQLs, even if it's "only an app to track your grandma's record collection"
...doesn't call functions on columns in the where clause - don't do it; it's a huge waste of resources and kills opportunities to use indexes. Always, always try to leave table data alone, untransformed. In 99% of cases there is another way to write the query
...uses executescalar - you only want one value, pointless using an adapter/table for it
...doesn't use column alises with spaces in - as noted in the comments - don't do it; it's not the database's job to format your column names, it's the front end's job.
Dim count_gradeSchool1 As String = "Select COUNT(*) as c
FROM training.userinfo
Where survey_at = #loc
And status = 'College'
And member_since = #ms"
Using c = New MySqlCommand(count_gradeSchool1, mycon)
c.Parameters.AddWithValue("#loc", txtmonthlylocation.Text)
c.Parameters.AddWithValue("#ms", new Date(CInt(txtmyear.Text), CInt(monthly_reports), 11)
c.Connection.Open() 'if it's not already open
lblgs1.Text = c.ExecuteScalar().ToString()
End Using

Related

Access with 1 MySQL Table asking for credentials

I have a access database using a local sql server backend for all tables except 1 web based MySQL table. The MySQL table has 50 rows or so, 3 fields, not big at all. I have a odbc connection setup and the table is linked with the password saved. This table is updated 30 times per day at most... Sometimes the connection breaks and the MySQL connection popup will appear... clicking test will result in a success, and clicking ok will allow the code to proceed. It is doing a 1 line update (SET LastUpdatedDate = #" & now() & "# WHERE ItemID = 'xyz').
I want to capture an error, or get it to continue without the connection if it is unavailable... but it appears no error is generated. I would rather not update the table when this happens, then have to physically select ok to get it running again. This problem exists from multiple locations, on multiple PCs around the US. I assume it is the server the MySQL db is hosted on that is having problems - I just want to know how to ignore them and move on with the other code... again, no error generated (So On Error ... won't work). Any Ideas? Using Access 2016.
UPDATE: My current setup is to ping the server... and if the ping gets a response, I assume it is up... then I run 'CurrentDb.Execute "UPDATE XYZ SET ABC = 'DEF' WHERE GHI = 'JKL'". That simple. If I try to query the table XYZ and it isn't available, I get the same connection popup. How should I go about refreshing the table? Delete the link and recreate?
NEW UPDATE
Finally got around to try out the DSN-less pass through query proposed by Andre below. When I get to the 'execute' step I get an error saying I cannot execute a select query... but it is an update query. Here is the SQL string... .SQL = "UPDATE [Status] SET ItemDate = NOW() WHERE PlantID = '" & PlantID & "' AND ItemID = '" & ItemID & "'"
I suggest that instead of running an Access query on the linked table, you use a DSN-less Pass-Through query that you create on the fly.
This should either always work, or raise a trappable error.
Const ConnectString = "ODBC;DRIVER={MySQL ODBC 5.1 Driver};SERVER=your.server.com;PORT=3306;DATABASE=mydatabase;UID=myuserid;PWD=mypassword"
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.CreateQueryDef("")
With qdf
' Setting .Connect turns it into a Pass-Through query
.Connect = ConnectString
' Need to set this for non-SELECT queries
.ReturnsRecords = False
' Note: you need to use MySql syntax here, not Access SQL, especially the correct date format
.SQL = "UPDATE XYZ SET ABC = 'DEF' WHERE GHI = 'JKL'"
' or since MySql has a NOW() function too, just this:
.SQL = "UPDATE foo SET LastUpdatedDate = NOW() WHERE ItemID = 'xyz'"
.Execute
End With
You can also try a saved Pass-Through query, it might work as well. Then you would only need to supply the current .Sql, not the connect string.
Maybe you will get an helpful error if you execute your SQL command with the option dbFailOnError ? Like CurrentDB.Execute("Your SQL", dbFailOnError)
Before trying the UPDATE, do a simple SELECT. If it does not return a reasonable result, assume that the connection is down.

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"'"

ASP Classic recordset unable to see columns with 'table.column_name' format after MySQL conversion

I am currently in the process of converting a large amount of ASP classic/VBscript pages from an old database (Unify Dataserver) to MySQL.
Say you have a query like this:
sql = "SELECT c.container_type, c_amount, c_sdate, c_edate, csrt " & _
"FROM containers c, container_chars cc"
objRS.Open sql, objConn, 3, 1
If I want to reference the column "c_edate", I can simply use this and it works fine:
x = objRS("c_edate")
However, when it comes to referencing a column like "c.container_type" (With a . used to differentiate it from another table, like so:
x = objRS("c.container_type")
It will say
ADODB.Recordset error '800a0cc1'
Item cannot be found in the collection corresponding to the requested name or ordinal.
I can fix it by using a number instead:
objRS(0)
This was never an issue until we switched to MySQL. In our old database, using the rs(table.column_name) format worked just fine. But in MySQL, once you add a (.) to the code, it can't find that item unless you switch it to a number.
As you can imagine, this is quite a pain as I go through the 700+ pages of this website manually counting the placement of each column in the corresponding select statement every time something from the query is referenced.
Does anyone know why this is happening or how to make the rs(table.column_name) format work with MySQL like it does with our old database?
In SQL Server, and apparently in MySQL too, the way to reference a field in the result set is to just use the name, without the prefix.
x = objRS("container_type")
The prefix is needed by the database to differentiate between identically-named columns, but once you send the results to a recordset, that recordset doesn't know or care where the columns came from.
The same goes for aliases:
SQL = "SELECT c.container_type AS ctype, [...]"
...
x = objRS("ctype")
Combining these two facts, if you do have identically-named columns in the result set, you must alias at least one of them. If you don't, it won't necessarily give an error, but you will not be able to reference the second column using the rs("name") syntax.
SQL = "SELECT c1.container_type, c2.container_type AS c_type2, ..."
...
x = objRS("container_type")
y = objRS("c_type2")
[Note that while you're at it, you probably should also modify your FROM clauses to use proper FROM table1 INNER JOIN table2 ON table1.fieldA = table2.fieldB type syntax. The FROM table1, table2 WHERE table1.fieldA = table2.fieldB syntax has been deprecated for many years now.]

C# MySql Syntax Exception when querying against an IP addres

I'm querying against an IP address stored in a table of a database with the following:
"SELECT user_id, is_login FROM users WHERE last_ip_address = '" + this.GetIPAddress() + "'"
I know that the IP is in the table because I see it there. I'm literally staring at it, but this query returns no rows.
When I run it without the single tick quotes ('), I get a syntax error:
"SELECT user_id, is_login FROM users WHERE last_ip_address = " + this.GetIPAddress()
So where is this going wrong? The IP returned by the function is the standard format ###.###.###.### IP address, and the syntax error itself is this:
{"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.##.#' at line 1"}
Edit: Some more info, the field itself is a varchar(30) type, and it says Collation = latin1_swedish_ci, but I don't even know what that is.
Thanks
Try using a LIKE then:
"SELECT user_id, is_login FROM users WHERE last_ip_address LIKE '%" + this.GetIPAddress() + "%'"
Edit: I would try to change that collation to UTF8.
Okay I am sorry for the confusion. I am very new to using MySql with C# and very VERY new (like I mean I just started today) with MySqlConnector.
To make a long answer short, I was trying to treat the table like, well, a table, and just read from it like a two dimensional array, when what I needed to be doing was using the MySqlDataReader. I found a good answer here:
How to read columns and rows with C#?
Thanks all for your help and advice.

SQL query is correct but still a "SQL error 1064" appears

I can't deal with it. I'm experiencing big troubles with this very query:
UPDATE books
SET books.out = books.out + 1
WHERE id = 81813130;
UPDATE books
SET books.available = 0
WHERE books.in = books.out;
If I run it on my phpMyAdmin, everything's fine and everything completes, but in my CakePHP application this query doesn't work and when I perform a debug this is what I'm told:
Warning (512): SQL Error: 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE books SET books.available = 0 WHERE books.in = books.out' at line 1**
I'm calling my query from a controller:
$this->Lending->update_lendings($this->data['Lending']['book_id']);
and the actual query is of course into the model:
$query = "
UPDATE books
SET books.out = books.out + 1
WHERE id = ".$id.";
UPDATE books
SET books.available = 0
WHERE books.in = books.out;
";
I really can't say why this isn't working. It seems that error 1064 Mysql is a very common question in here but I didn't find anything useful about my very issue.
I steadfastly thank you for your support and help.
It looks like your problem might be due to PHP's lack of support for Multiple Statement Execution. Multiple Statement Execution allows you to run two queries in a single request and receive multiple result-sets in response.
MySQL DOES support it, but the default setup in PHP prevents this (that is, if you're using the deprecated mysql_connect() era functions). This is actually a nice default because there are some serious bugs that can be introduced by allowing multiple-queries (see SQL injection).
So, the solution could be to alter your code to request the data separately.
$query = "
UPDATE books
SET books.out = books.out + 1
WHERE id = ".$id.";";
mysql_query($db, $query);
$query = "UPDATE books
SET books.available = 0
WHERE books.in = books.out;";
mysql_query($db, $query);
That being said, if you think that it's safe enough to use multi-statements (that is, if all of the input values are sanitized), then go ahead and try to use the mysqli functions (there not even deprecated!).
mysqli_multi_query( $query ) should give you the flexibility you need.
aparently, it's because you use reserved words in your query, try and escape all table names and table columns in ``
list of reserved words in mysql available here
If the second Update statement is meant to change only the row that the first statement updated, then you could use a single Update:
UPDATE books
SET out = out + 1
, available = CASE WHEN in = out
THEN 0
ELSE available
END
WHERE id = 81813130