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

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 ;

Related

JMeter sql syntax error using parameters with insert

I'm working with JMeter to load test queries on a mySQL database (memsql server, mySQL syntax). I'm using a gui version of JMeter to create a test plan xml file and then go to another server and run that xml in non-gui mode.
I have two queries running, one that selects and one that inserts. Both queries use parameters taken from a csv file I made with a script.
My SELECT statement works just fine with parameters taken from a csv file but I run into syntax errors with my INSERT statement:
INSERT INTO customer_transactions_current (`column_name1`, ... , `column_name12`)
VALUES ((${r1},${r2},${r3},${r4},${r5},${r6},${r7},${r8},${r9},${r10},${r11},${r12}));
In the section of the query in the gui mode under 'CSV Data Set Config' I choose to delimit the data by ',' and the variable names are r1,..,r12.
Under the query itself I entered the parameter types and again the same names, just as I did for the working SELECT query.
When I run the query I run into a syntax error on the first column (which is of type datetime):
java.sql.SQLSyntaxErrorException: 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 '19:00:00,75400492,936988,56,1115,5,2156,8,2,3,909,3))' at line 2
The dates I'm entering are of the form: '2018-11-2 20:00:00' and in the csv file they are present without apostrophes.
It seems that the syntax error has something to do with the date and in the position where it holds a space. I tried entering the STR_TO_DATE function for that column but kept getting syntax errors.
BUT when I try to take some values from the file and manually run the query it works fine! So my thoughts are that it has something to do JMeter's conversion of spaces before sending out the query.
Is the problem with my configurations of JMeter? Since the query is OK manually.
Add apostrophes to insert and remove unnecessary parenthesis
INSERT INTO customer_transactions_current ('column_name1', ... , 'column_name12')
VALUES ('${r1}','${r2}','${r3}','${r4}','${r5}','${r6}','${r7}','${r8}','${r9}','${r10}','${r11}','${r12}');
If you have date issue see using STR_TO_DATE

SQL syntax error has occurred

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.

Syntax error when trying to create a database with name: 9e1617bafr1_1

yesterday I stumbled upon a weird problem.
I have a PHP script that creates mysql databases for me based of some input.
When the script tried to generate a database with the name "9e1617bafr1_1" (without quotes) and I got this error "MySQL Error 1064: You have an error in your SQL syntax".
Query is CREATE DATABASE IF NOT EXISTS 9e1617bafr1_1
I also get the error when trying to execute it on https://de.piliapp.com/mysql-syntax-check/ and http://sqlfiddle.com/
I resolved it by using backticks before and after the database name but I'm still wondering why I got this error in the first place as the creation of "9d1617bafr1_1", "9f1617bafr1_1" and so on worked flawlessly.
Unfortunately I did not find anything useful on this behavior on the internet and as I'm very curious about it I wanted to ask if anybody know if this is a reserved word or if it violates the SQL standard in any way?
9e1617bafr1_1 is parsed as number (9e1617) followed by a character string (bafr1_1). Your other attempts, "9d1617bafr1_1", and "9f1617bafr1_1", don't start with scientific notation, so they don't get parsed that way.

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.

Mysql function return system result

In mysql, I'm trying to create a function that will return the result of a bash command. I've created a simplified version of what I'm trying to do to make it easier to understand.
I have a file called mycmd.sh, and inside it, I have this line:
echo $1 'test'
When in mysql, I execute the sh file it is working fine
system ~/mycmd.sh 'test'
But I would like to be able to call it while doing a select in mysql, something like this
select myFunc(username) from user;
The result will be that, every username will have a "test" after it.
The problem is when I try to create the mysql function
CREATE FUNCTION myFunc(s VARCHAR(500)) RETURNS VARCHAR(505)
RETURN SYSTEM ~/mycmd.sh s;
I always get the error: ERROR 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 '~/mycmd.sh s' at line 2
I tried putting it in quote, or in a variable, or in a prepared statement, but nothing seem to work...
Anyone have an idea how to do so?
Thank you
Unfortunately what you are trying to do isn't possible without using a UDF (User Defined Plugin). The system command you're using is part of the MySQL shell, not an actual MySQL function, which is why it doesn't work in the function you're trying to define.
The only other option I can think of is to write a procedure that imitated whatever your external command was going to do.