SQL syntax error has occurred - mysql

Here is my simple query:
my $SQLp = "SELECT MAX([PawnPayments].[CreationTimeDate]) as MaxTransDate
FROM [PawnSafeDBCE].[dbo].[PawnPayments]
INNER JOIN [PawnSafeDBCE].[dbo].[PawnPaymentDetails]
ON [PawnPayments[.[PaymentID] = [PawnPaymentDetails].[PaymentID]
WHERE [PawnPaymentDetails].[TicketID[ = '$TicketID'
AND [PawnPaymentDetails].[StoreID] ='$StoreID'
Note that query is written on Perl engine. I keep receiving an error that says:
"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 '[PawnPayments].[CreationTimeDate]) as MaxTransDate:"
I believe the error has to do with the bracket notation, but unfortunately, I am having to use this style due to a poorly constructed 3rd party table. Any help? Am I missing something obvious?
Huge EDIT: The table I am querying is actually on a SQL server, not a MySQL server! My database runs on the MySQL server, but this 3rd party database runs on an older version of Microsoft SQL.

I don't know why you have all those square brackets around your table and column names, but they aren't necessary and they aren't standard SQL. That's what is causing your syntax error.
my $SQLp = "SELECT MAX(PawnPayments.CreationTimeDate) as MaxTransDate
FROM PawnSafeDBCE.dbo.PawnPayments
INNER JOIN PawnSafeDBCE.dbo.PawnPaymentDetails
ON PawnPayments.PaymentID = PawnPaymentDetails.PaymentID
WHERE PawnPaymentDetails.TicketID = '$TicketID'
AND PawnPaymentDetails.StoreID ='$StoreID'";
I'll also add that having variables interpolated in your SQL statement like that is potentially leaving you open to SQL injection attacks. Far better to use bind points in your SQL and use extra arguments to execute to fill in the values (assuming you're using DBI).
my $SQLp = "SELECT MAX(PawnPayments.CreationTimeDate) as MaxTransDate
FROM PawnSafeDBCE.dbo.PawnPayments
INNER JOIN PawnSafeDBCE.dbo.PawnPaymentDetails
ON PawnPayments.PaymentID = PawnPaymentDetails.PaymentID
WHERE PawnPaymentDetails.TicketID = ?
AND PawnPaymentDetails.StoreID = ?";
my $sth = $dbh->prepare($SQLp);
$sth->execute($TicketID, $StoreID);
Update: As Bill Karwin points out in a comment, the database.schema.table syntax makes no sense in a MySQL database. So I think you're a little confused. The error message you are getting definitely mentions MySQL, so you're connecting to a MySQL server, using DBD::MySQL - but perhaps you should be connecting to an MSSQL server instead.
It might be useful if you showed us your database connection code - the call that sets up your $dbh (or equivalent) variable.

You say you are querying a MS SQL database, but the error message clearly says you are using a MySQL database or a MySQL database driver.
If you are querying a MS SQL database, fix your connection string.
If you are querying a MySQL database, use a MySQL-compatible query. MySQL uses backticks to quote identifiers (not square brackets like MS SQL).
[PawnPayments].[CreationTimeDate]
should be
`PawnPayments`.`CreationTimeDate`
Note that your code suffers from injection bugs due to incorrect quoting of value inserted into the SQL query. (It's not good enough just to put quotes around the values!) These can cause your code to fail, and they could make you vulnerable to injection attacks. Fix the quoting, or use replaceable parameters.

Related

MySql.EntityFrameworkCore generating invalid SQL syntax on SaveChanges

I am trying to use .NET 7 and EntityFramework with MySQL.
I am using MySql.EntityFrameworkCore v7.0.0 installed via NUGET.
I am able to scaffold my context and entities ("reverse engineer / db first"). Also I can successfully use the generated DbContext and query the entities.
When I attempt to do an update to an entity I get a MySqlException on calling SaveChanges().
MySqlException: 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 'RETURNING row_updated_time;
I did some Google searches and I can see that the keyword RETURNING is not valid syntax in MySql (but it is valid syntax in Oracle and PostGres -- this is interesting, and odd).
The complete SQL that is generated for this UPDATE (amounting to two SQL statements in one call):
UPDATE `state_agency` SET `abbreviation` = #p0
WHERE `code` = #p1
RETURNING `row_updated_time`;
SELECT `row_updated_time`
FROM `state_agency`
WHERE ROW_COUNT() = 1 AND `code` = #p1;
Is this problem familiar to anyone?
Can you suggest a possible reason why I am seeing Oracle/Postgres syntax get generated by the MySql provider?
My gut tells me that there is some sort of configuration problem and the Oracle syntax is coming out of a different provider, rather than the MySql provider.
I just ran into this exact problem and after some additional research found out the keyword RETURNING is valid mySQL syntax added in version 8.0.21
https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-8-0-detailed-R
This got me headed down a versioning mismatch direction. Eventually I landed here:
https://www.nuget.org/packages/Pomelo.EntityFrameworkCore.MySql
I figured out in my case the server's version of mySQL was 5.7.29 and I had to specify that.
var connectionString = "server=localhost;user=root;password=1234;database=ef";
var serverVersion = new MySqlServerVersion(new Version(5, 7, 29));
// Replace 'YourDbContext' with the name of your own DbContext derived class.
services.AddDbContext<YourDbContext>(
dbContextOptions => dbContextOptions
.UseMySql(connectionString, serverVersion)
);

mysql-connector-python adds single quotes around table name when table is passed as argument. Table name comes from Flask session variable

I am new to MySQL and I am building a Flask project and using mysql.connector to query a MySQL Database. I know this question has been answered many times before but this is more specific to using MySQL with Flask.
I need to pass a query where I want to plug in the table name into the query, dynamically, depending on the value stored in the session variable in Flask. But the problem is, if I try to do:
Method 1:
cur.execute('SELECT * FROM %s;',(session['table_name'],))
the database throws an error stating that such a table is not found. However, the problem is mysql.connector keeps enclosing the table name with single quotes, hence the error.
Sample Error Statement:
mysql.connector.errors.ProgrammingError: 1064 (42000): 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 ''52_data'' at line 1
Here the table name should be 52_data and not '52_data'.
Only other workaround, I figured, is using:
Method 2:
cur.execute('SELECT * FROM '+session['table_name']+';')
which is working but it does not escape SQL Injection, I am guessing, since it's direct concatenation, unlike Method 1, where the cur.execute() function handles the escaping, as per this question.
The value being passed is stored in a sessions variable in Flask, which is not so secure, as per Miguel's Video. Hence, I want to escape that string, without triggering off an error.
Is it possible to implement Method 1 in a way that it does not add the quotes, or maybe escape the string using some function? Or maybe any other Python/Flask package that can handle this problem better?
Or if nothing works, is checking for SQL Injection manually using regex is a wiser option?
Thanks in advance.
Note: The package name for this mysql.connector is mysql-connector-python and not any other same sounding package.
For identifiers, you can use something like:
table_name = conn.converter.escape(session['table_name'])
cur.execute('SELECT * FROM `{}`'.format(table_name))
For values placeholders, you can use your Method 1, by using the parameters in the cur.execute() method. They will be escaped and quoted.
More details in https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
NOTE: You don't need to end the SQL statements with ;

You have an error in your SQL syntax near '<!

Trying to relocate a Wordpress DB and are running in to this issue all the time.
Been trying all the normal stuff to get it working optimizing, repairing etc and also try to import it with several tools (Sequel pro etc ) and over ssh.
Have the issue occurring over several tables and can see that other's have had the same. Because i can't import any copy i would need some expertise advice how to solve this either in phpmyadmin or ssh.
Error message is
#mysql -u -p db < /tmp/file.sql
> ERROR 1064 (42000) at line 109088: 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 '<!
> <div class="error"><h1>Error</h1> <p><strong>SQL query:</strong> <a href=' at line 1
Don't really know how to approach it because i find this all over the DB
like
<image:caption><![CDATA
Any advice?
Since "all the normal stuff" isn't working...
I'm going to take a guess, you are a running something to "copy" the contents of a database table, or you're doing some sort of "dump" or "export" that creates SQL statements.
And the SQL statements that are running against the target are throwing an error.
We can't tell (from where we're sitting and what we're seeing) what it is you are actually doing, we're just guessing.
The two most likely possibilities:
Whatever tool you are using isn't expecting that the column values being copied might contain values that need to be "escaped" if that value is incorporated in the text of a SQL statement. For example, suppose I have a column value like this:
I'd like a pony
and If I grab that value and I naively stick that into the text of a SQL statement, without regard for any characters it might contain, e.g.
INSERT INTO foo (bar) VALUES ('I'd like a pony');
If I try to execute that statement, MySQL is going to throw a syntax error. MySQL is going to see a string literal with a value of 'I' (the single quote that is part of the string is now being seen as the end of the string literal. MySQL is going to flag a syntax error on what follows d like a pony.
When we take a value and build a SQL statement from it, we have to properly escape the values. In this example, the insert statement to reproduce that string value could look like this:
INSERT INTO foo (bar) VALUES ('I''d like a pony');
^^
If this is what's happening, you can be thankful that the column values didn't include something more nefarious...
Robert'); DROP TABLE students; --
But without seeing the actual SQL statement that is being executed, this is just a guess at what is causing the issue.
Is there some kind of guide or some instructions that you are following to "relocate a Wordpress DB" which documents "all the normal stuff" that you are doing?
FOLLOWUP
Question was edited to add this information:
mysql -u -p db < /tmp/file.sql
What's important here is the contents of file.sql.
The problem is most likely in the part of "all the normal stuff" is producing that file. That part is effectively broken because it's not expecting that an extracted column value can contain a single quote character, and is not properly escaping the value before it's incorporated into the text of a SQL INSERT statement.

(ASP) MS Access -> MySQL: Error in Select, where [..] strings

I am using a portal system on my website and modified the ASP code heavily.
Since the website is growing, I want to migrate from MS Acces to MySQL.
Now, I think the portal I'm using (and some code I inputted) aren't MySQL compatable, because when I switch to the MySQL database, I get the following error.
Microsoft OLE DB Provider for ODBC Drivers error '80040e14'
[MySQL][ODBC 5.1 Driver][mysqld-5.1.55-community]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 '[EzModuleID],
[ModName] From EzCore_Plugin Where IsModActive='1'' at line 1
[website]\WWWROOT\BOXX\INCLUDES../../includes/include.asp, line 3736
The SQL string regarding this line is the following:
Select [EzModuleID], [ModName] From EzCore_Plugin Where [IsModActive] = 1;
Im new to MySQL and I can't find why this is giving an error.
I've tried the quote's around 1, removing [], removing the space..
I think that when I figure out why this is causing an error, I can continue modifying the rest to make the website work on mysql.
Lose the square brackets
(I might as well post this as the answer rather than a comment)
In MySQL column and table names can be escaped with the backtick character ` or if the ANSI SQL mode is enabled with double quotes ".
Your WHERE clause (according to the error message) is Where IsModActive='1'. This works if IsModActive is a text column. If it is numeric, drop the single quotes. If IsModActive is a Boolean, change the clause to Where IsModActive IS true.
See: is operator

Migration from SQL Server 2008 to Azure

I'm using SQLAzureMW v3.8.8 but I get lots of errors in the script generated. And the problem is that i don't know in which line is each error generated.
Error #: 105 -- Unclosed quotation mark after the character string
'CREATE PROCEDURE [dbo].[spAdminParametrosGet]
Error #: 156 -- Incorrect syntax near the keyword 'ELSE'.
Error #: 40512 -- Deprecated feature 'NOLOCK or READUNCOMMITTED in
UPDATE or DELETE' is not supported in this version of SQL Server.
Incorrect syntax near '
The TSQL script generates sql stored procedures as strings and are created using dynamic SQL. Some stored procedures have comments inside of it.
May that be the cause or any suggestion to quickly migrate the database to Azure?
It is very much possible that some of the SP and other statements which you want to migrate from SQL Server to SQL Azure are not compatible. Here is a list of supported and unsupported TSQL features:
http://msdn.microsoft.com/en-us/library/windowsazure/ee336250.aspx
Also you haven't mentioned what is your source SQL Server is? As not all SQL Server will full features are supported by SAMQ (3.8 or 4.01)
Also please match your TSQL statements from the unsupported list below and check if any of listed below are part of your TSQL statements:
http://msdn.microsoft.com/en-us/library/windowsazure/ee336253.aspx